Angular4 - 嵌套的 Http 调用 [英] Angular4 - Nested Http Calls

查看:19
本文介绍了Angular4 - 嵌套的 Http 调用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 angular 中使用 http 嵌套调用.

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());
      })
  }

函数返回Promise>.如何解析响应,以便我可以从订阅中的嵌套调用中获取数据.

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);
      });

推荐答案

你可以使用 RxJS 操作符,例如 switchMap 来简化这个嵌套调用并且不使用 toPromise().

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

映射到 observable,完成之前的内部 observable,发出值.

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

您有效地将第一个 observable 发出的值传递给下一个 observable(您的第二个 HTTP 调用).这允许您订阅使用示例中的最终结果.

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.

重要的是,在 switchMap() 中,您return 内部 observable,在这种情况下,HTTP 调用使其有效运行.

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

正如其他人指出的,toPromise() 不是必需的,因为您可以利用 RxJS 操作符来完成这个异步的、依赖的操作.

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());
}

使用

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

注意:使用 Angular 4+ HttpClient,您不需要不需要在响应上显式调用 json(),因为它会自动执行.

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

这篇关于Angular4 - 嵌套的 Http 调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆