1

I'm using a http nested call in angular.

First Call to get a token. Second call will be using token and returning actual data.

  public get(api) {
    return this.http.get(this.url + '/token')
      .map(res => res.json())
      .toPromise()
      .then((data: any) => {
        this.access_token = data.access_token
        let headers = new Headers();
        headers.append('Authorization', 'Bearer ' + this.access_token);
        return this.http.get(this.url + api, {
          headers: headers
        }).map(res => res.json());
      })
  }

The function returns Promise<Observable<any>>. How to parse the response so i can get the data from nested call in a subscription.

this.get('me/profile')
    .subscribe(data => {
         console.log(data);
      });
Alexander Staroselsky
  • 37,209
  • 15
  • 79
  • 91
Sumit Ridhal
  • 1,359
  • 3
  • 14
  • 30
  • 1
    Try removing the `.toPromise()`. That should return an `Observable`. I recommend you to use type (`Class`) to map data so the results are object rather than JSON strings. Like Java. – Prav Aug 28 '17 at 20:27
  • 2
    Either be consistent with promises (return a promise from then callback) or observables (flatmap over the second call). Mixing is a recipe for disaster. – jonrsharpe Aug 28 '17 at 20:28
  • You're mixing two different methods of handling async data, which is hellish in it's own right. Either produce Promise Chaining to get the data, use .then or switch away from the conversion to a promise being returned in your get function. – L.P. Aug 28 '17 at 20:29

1 Answers1

6

You could use RxJS operators such as switchMap to streamline this nested call and without using toPromise().

Map to observable, complete previous inner observable, emit values.

You are effectively passing emitted values of first observable to the next observable (your second HTTP call). This allows you subscribe to the final results in your usage example.

It is important that within the switchMap() you return the inner observable, in this case the HTTP call for this to function effectively.

As others have indicated, toPromise() is not necessary as you can take advantage of RxJS operators to complete this async, dependent action.

public get(api) {
  return this.http.get(this.url + '/token')
    .map(res => res.json())
    .switchMap(data => {
        this.access_token = data.access_token;
        let headers = new Headers();
        headers.append('Authorization', 'Bearer ' + this.access_token);

        return this.http.get(this.url + api, { headers: headers });
    })
    .map(res => res.json());
}

usage

this.get('me/profile').subscribe(data => console.log(data));

Note: With Angular 4+ HttpClient, you don't need to explicitly call json() on the response as it does it automatically.

Dharman
  • 30,962
  • 25
  • 85
  • 135
Alexander Staroselsky
  • 37,209
  • 15
  • 79
  • 91
  • At the very minimum you can try using the catch operator, but I'd check out the following [discussion](https://github.com/Reactive-Extensions/RxJS/issues/829) on strategies to handling the inner errors. Thanks! – Alexander Staroselsky Nov 29 '17 at 13:51
  • The link you provided has nothing related to switchmap and subscribe. – Hrushikesh Patel Nov 29 '17 at 14:08
  • The link describes error handling with "nested" observables such as `flatMap()`. The same strategies can be used, including `catch()` and `Observable.just()`. The syntax may look slightly different, but it's the same principles. There is no one right way to approach this, it really depends on the application and situation. There are also questions on Stack Overflow such as [this](https://stackoverflow.com/questions/38649652/rxjs-catch-error-and-continue) describing similar strategies. Thanks! – Alexander Staroselsky Nov 29 '17 at 15:13