Sorry for the bad title, I really didn't have a good idea how to phrase it.
Let's assume I have a service call somewhere in an Angular component like:
this.myService.postObject(object).subscribe((serverData) => {
console.log('Server Name:' + serverData.name)
});
This works perfectly of course when the MyService looks like:
postObject(dataObject: MyObject) {
return this.http.post(`http://server/object`, dataObject);
}
But what when I want to react on the async result not only individually in only subscriptions but additionally generally for all calls - so ideally like this:
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.
But I think of logging, messaging and other general activities which need to be done when the post was executed.
Is there a way to achieve this or am I just blind to see? :-(
This is what 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 instead
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.