在Angular 2中有两个http.get调用的可观察类型

时间:2016-10-04 11:28:42

标签: javascript angular typescript

在我的ng2服务中,我有一个有2个http.get调用的方法。 该函数看起来像这样:

getInfo(userId: number): any {

    this.http
       .get(apiUrl, options)
       .map(response => response.json())
       .subscribe(example => {
           this.example.FirstName = example.FirstName;
           this.example.LastName = example.LastName;

           this.http
               .get(`/api/${userId}`)
               .map(response => response.json())
               .subscribe(example => {
                   this.example.Street = example.Street;
                   this.example.City = example.City;

                   return this.example;
               });
       });
 }

唯一的问题是,在我的组件中,我无法订阅此功能,因为它不属于Observable<Example>类型。

如果我用[{1}}替换函数的类型any,我得到:

声明类型既不是&#39;无效的函数。也没有任何&#39;必须返回值

但是在回复之后我确实会返回一个值。

如果没有两个单独的功能,我怎么能这样做?

是的,我确实检查了这个答案:https://stackoverflow.com/a/36712707/3264998

2 个答案:

答案 0 :(得分:3)

尝试将此作为您的方法体,这是解决此问题的其他方法之一。

return this.http
   .get(apiUrl, options)
   .map(response => response.json())
   .flatMap(example => {
       this.example.FirstName = example.FirstName;
       this.example.LastName = example.LastName;

       return this.http
           .get(`/api/${userId}`)
           .map(response =>  {
               let example =response.json();
               this.example.Street = example.Street;
               this.example.City = example.City;

               return this.example;
           });
   });

答案 1 :(得分:1)

我的解决方案使用rxjs / Rx flatMap:

import {Observable} from 'rxjs/Rx';


ngOnInit() {
  const usersId = ['USR001', 'USR003'];
  this.doRequest(usersId);
}

doRequest(queryArr, previousObservable = null) {
        if (queryArr.length) {
            const url = 'api/' + queryArr.shift();
            let observable = null;
            if (previousObservable) {
                observable = previousObservable.flatMap(() => {
                    return this.http.get(url);
                });
            } else {
                observable = this.http.get(url);
            }
            return this.doRequest(queryArr, observable);
        } else {
            return previousObservable;
        }
    }
相关问题