5

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.

Andrew Gray
  • 3,756
  • 3
  • 39
  • 75
  • 3
    Is the 3rd snippet what you're actually using or a pseudo example? You need parenthesis around the callback arg when typed. `mergeMap( (radResult: MyRadModel) => ....` – Phix Feb 11 '19 at 18:17
  • 2
    As @Phix mentioned, you have to enclose args in a parenthesis when your args are typed or if you have multiple args (typed or non typed). – Amit Chigadani Feb 11 '19 at 18:37
  • 1
    Can you try using `concatMap` instead? It preserves order while `mergeMap` doesn't. – Phix Feb 11 '19 at 18:41
  • @Phix et al - On the parentheses: "Oops." I forgot that, my bad. That helps, actually. Good ol' ID-10T error on my part. :( – Andrew Gray Feb 11 '19 at 19:43
  • 1
    You might take a look at: https://stackoverflow.com/questions/40788163/how-to-make-nested-observable-calls-in-angular2 which uses flatMap() – Brandon Taylor Feb 11 '19 at 20:28

0 Answers0