Return 从服务订阅 - 但如何在服务中也使用异步结果?
Return Subscription from Service - but how to use async result also in Service?
抱歉,标题不好,我真的不知道该如何措辞。
假设我在 Angular 组件中的某处有一个服务调用,例如:
this.myService.postObject(object).subscribe((serverData) => {
console.log('Server Name:' + serverData.name)
});
当 MyService 看起来像这样时,这当然可以完美地工作:
postObject(dataObject: MyObject) {
return this.http.post(`http://server/object`, dataObject);
}
但是,当我不仅想对订阅中的异步结果做出反应,而且还想对所有调用做出反应时,该怎么办——理想情况下是这样的:
postObject(dataObject: MyObject) {
return this.http.post(`http://server/object`, dataObject)
.subscribe(
(serverData) => {
console.log('Server Name:' + serverData.name)
})
}
This of course doesn't work as I can't return the .subscribe and then .subscribe again to it.
但我想到了在执行 post 时需要完成的日志记录、消息传递和其他一般活动。
有没有办法实现这个,还是我瞎了眼? :-(
这是tap is for, tap is not going to modify your returning observable but can take care of things like logging. If you want to modify the returned Obsertvable, use map而不是
postObject(dataObject: MyObject) {
return this.http.post(`http://server/object`, dataObject)
.pipe(tap(serverData => {
console.log('Server Name:' + serverData.name)
}))
}
The RxJS tap operator (as in "wiretap") lets the code inspect good and error values passing through the observable without disturbing them.
抱歉,标题不好,我真的不知道该如何措辞。
假设我在 Angular 组件中的某处有一个服务调用,例如:
this.myService.postObject(object).subscribe((serverData) => {
console.log('Server Name:' + serverData.name)
});
当 MyService 看起来像这样时,这当然可以完美地工作:
postObject(dataObject: MyObject) {
return this.http.post(`http://server/object`, dataObject);
}
但是,当我不仅想对订阅中的异步结果做出反应,而且还想对所有调用做出反应时,该怎么办——理想情况下是这样的:
postObject(dataObject: MyObject) {
return this.http.post(`http://server/object`, dataObject)
.subscribe(
(serverData) => {
console.log('Server Name:' + serverData.name)
})
}
This of course doesn't work as I can't return the .subscribe and then .subscribe again to it.
但我想到了在执行 post 时需要完成的日志记录、消息传递和其他一般活动。
有没有办法实现这个,还是我瞎了眼? :-(
这是tap is for, tap is not going to modify your returning observable but can take care of things like logging. If you want to modify the returned Obsertvable, use map而不是
postObject(dataObject: MyObject) {
return this.http.post(`http://server/object`, dataObject)
.pipe(tap(serverData => {
console.log('Server Name:' + serverData.name)
}))
}
The RxJS tap operator (as in "wiretap") lets the code inspect good and error values passing through the observable without disturbing them.