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

查看:157
本文介绍了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<Observable<any>>.如何解析响应,以便我可以从订阅中的嵌套调用中获取数据.

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运算符,例如

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.

您正在有效地将第一个可观察到的发射值传递给下一个可观察到的值(您的第二个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内部可观察到,在这种情况下,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天全站免登陆