RxJs循环返回数组

时间:2018-07-27 00:26:24

标签: angular rxjs angular2-observables rxjs-pipeable-operators

有没有比RxJS运算符更好的方法来循环从可观察对象返回的数组,而不是发出新的单独的ListingItem?

onGetItemData(){
this.dataService.getItemData().subscribe((itemData) =>
{
  this.itemDataJSON = itemData;
  this.itemDataJSON.forEach(function (value) {
    let new_listing = new ListingItem(value.label,value.market,value.name);
    console.log(new_listing);
  });
 });
}

API返回包含项的单个数组,因此我无法使用.map访问itemData.name

//-- DataService --// 
getItemData(){
 return this.http.get(this._URL, { headers })
        .pipe(map((res: Listings) => res.items))
}

2 个答案:

答案 0 :(得分:5)

为什么不只管道map()

this.dataService.getItemData()
    .pipe(
        map(itemData => {
            return itemData.map(value => {
                return new ListingItem(value.label, value.market, value.name);
            })
        })
    )
    .subecribe((listingItem) => {
        console.log(listingItem) // gives an array of listingItem
    });

请注意,.map()实际上是JavaScript的本机数组函数,您将通过遍历数组的每一项来使用它来转换数据

只需一个班轮代码:

.pipe(
    map(itemData => itemData.map(value => new ListingItem(value.label, value.market, value.name)))
)

答案 1 :(得分:2)

我仍在自己学习Observables,但我认为您可以像在StackBlitz中一样从数组创建Observable:https://stackblitz.com/edit/angular-tbtvux

简而言之(在Angular 6中):

import { from, pipe } from 'rxjs';
...
let observable = from([10, 20, 30])
  .subscribe(v => console.log(v));

因此,也许您可​​以在可观察对象上通过管道传递switchMap运算符,以返回一个数组,如下所示:

import { switchMap } from 'rxjs/operators';
...
yourArrayObservable$.pipe(
  switchMap(val => from(val))
);

...然后您可以像这样使用地图:

import { switchMap, map } from 'rxjs/operators';
...
yourArrayObservable$.pipe(
  switchMap(val => from(val)),
  map(val => val * 42)
);

...至少在我前面提到的StackBlitz中似乎有效。


更新:我认为flatMap运算符也可以使用单个运算符类似地工作:

yourArrayObservable$.pipe(
  flatMap(val => val * 42)
);
相关问题