具有可迭代数组和合并resutls的Angular 2链http请求

时间:2016-07-25 01:43:47

标签: typescript angular rxjs rxjs5

新角色与flatMap函数混淆。

export interface IProduct {
    productId: number;
    productName: string;
    versionUrl: string;
    versionObj: any;
}

product.service.ts:

第一个HTTP请求返回IProduct个对象的数组。 使用产品对象中的versionUrl为每个产品发出HTTP请求,并将生成的对象映射到product.versionObj

product.versionObj ==>应该映射到每个产品的HTTP请求的结果。

getAllProductsWithAddlInfo(): Observable<IProduct[]> {
      return this._http.get('products.json')
             .flatMap((response: Response) => response.json())
             .flatMap((product: IProduct) => this._http.get(product.versionUrl), 
                     (product: IProduct, resp) => resp.json())   

产品list.component.ts:

products: IProduct[];

/* 
I would like to get an array of products with the additional info object 
mapped to versionObj from the http call for each product 
*/

ngOnInit(): void {
     this._productService.getAllProductsWithAddlInfo()
        .subscribe(
            products => this.products = products,
            error => this.errorMessage = <any>error);

    console.log(this.products);
}

1 个答案:

答案 0 :(得分:0)

您可以使用Observable.toArray()

getAllProductsWithAddlInfo(): Observable<IProduct[]> {
    return this._http.get(
        'products.json'
    ).flatMap(
        (response: Response) => response.json()
    ).flatMap(
      (product: IProduct) => this._http.get(product.versionUrl),
      (product: IProduct, resp) => {
        product.versionObj = resp.json();
        return product;
        // or simply: (product.versionObj = resp.json(), product)
      }
    ).toArray();
}

但是更改调试功能(在ngOnInit())以在下一个事件之后打印(否则它将在观察者发出任何值之前打印):

ngOnInit(): void {
  this._productService.getAllProductsWithAddlInfo()
    .subscribe(
      products => {
        this.products = products;
        console.log('Products: ', this.products);     // console.log() move to here
      },
      error => this.errorMessage = <any>error
    );
}

Demo plunker here