Angular 2 - 同时根据不同的上下文进行多个HTTP get请求?

时间:2017-11-22 17:54:09

标签: angular angular-http

我的REST呼叫服务有不同的url上下文来获取不同的数据。我想在同一时间发出一个HTTP get请求,并将响应映射到三个不同的下拉列表。

我的代码:

protected getCodes1(): string {
        const apiConfig = 'http://www.example.com/context1'; (need to change the context based on parameter)
        if (!uri) {
            throw new Error('Missing API);
        }
        return uri;
 }
 protected getCodes2(): string {
        const apiConfig = 'http://www.example.com/context2'; (need to change the context based on parameter)
        if (!uri) {
            throw new Error('Missing API);
        }
        return uri;
 }
 protected getCodes3(): string {
        const apiConfig = 'http://www.example.com/context3'; (need to change the context based on parameter)
        if (!uri) {
            throw new Error('Missing API);
        }
        return uri;
 }

我的HTTP电话:

const getCodesList1 = getCodes1();
const getCodesList2 = getCodes2();
const getCodesList3 = getCodes3();
this.http.get('getCodeList1'),
this.http.get('anotherurl'),
this.http.get('anotheranotherurl'),
(response1, response2, response3) => {
    //do something to put them all together
    //return a single object
}
).subscibe(finalObject => ...)

我没有得到正确的回复。请给我一些线索来获取这些东西......感谢一些线索..

1 个答案:

答案 0 :(得分:0)

forkJoin

检查mergeMapRxJS运营商

示例:

ngOnInit() {

    let character = this.http.get('https://swapi.co/api/people/1');
    let characterHomeworld = this.http.get('http://swapi.co/api/planets/1');

    forkJoin([character, characterHomeworld]).subscribe(results => {
      // results[0] is our character
      // results[1] is our character homeworld
      results[0].homeworld = results[1];
      this.loadedCharacter = results[0];
    });
  }