For a project I'm working on, my team and I are using Angular 7. We're kind of new to Angular 7, so we're all cooperatively learning about how some things work, as compared to AngularJS, which we've used for a few years.
I was reading some recommendations on anti-patterns in Observables, and noticed an example like the following:
this.http.get<MyRadModel>(`api/example/rad/${this.someId}`)
.mergeMap(radResult => {
// ... Instructions ...
return this.http.get<SomeOtherModel>(`api/example/other/${radResult.something}`)
})
.subscribe(otherResult => {
// ... Chained instructions! ...
});
Needless to say, you have to use .pipe()
to do this in Angular 6+ due to changes in RxJS, so actually applying this looks a little different...
this.http.get<MyRadModel>(`api/example/rad/${this.someId}`)
.pipe(
mergeMap(radResult => {
// ... Instructions ...
// Problem #1: 'Property something does not exist on radResult'.
// ... It actually *does*.
return this.http.get<SomeOtherModel>(`api/example/other/${radResult.something}`);
}
)
.subscribe(otherResult => {
// ... Chained instructions ...
});
One problem I noticed is that it seems that the recommended way of chaining Observables
doesn't let us use models when we're using mergeMap
. Further, as a side note, using typing annotation:
.pipe(
mergeMap(radResult: MyRadModel => {
// Problem #2: 'Cannot find name radResult.'
})
)
...Causes errors too.
Question: What's a good way to chain Observables
in Angular 7, that allows me type safety and access to the properties of things that I need to use in the interstitial Observable.subscribe
calls that seem to be happening? As noted, a number of earlier Angular tutorials and recommendations on best practices seem broken due to change in RxJS.
Side note: Bear in mind that I'm a newcomer to the RxJS way of doing things; I'm an AngularJS veteran. I know just enough about RxJS to know I know little. It's possible that I'm applying the wrong technique to chaining Observable.subscribe
calls.