Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
150 views
in Technique[技术] by (71.8m points)

javascript - Angular4 - Nested Http Calls

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);
      });
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...