首页 > 解决方案 > RxJS operator with array

问题描述

I think I have a misunderstanding on how works RxJS with an array when I receive it from an HTTP call.

For example I have:

  public getNews(): Observable<News[]> {
    return this.http.get<News[]>("/news");
  }

And after I want to use a simple map on it:

this.newsService.getNews().pipe(map(news => {
    return {
      // DO SOMETHING HERE WITH NEWS
    };
}));

The problem is the type of my param, Typescript told me its a array of News but it's inside a map so normally it has to of type News right?

I don't know If I'm clear, but if someone can explain me it would be great :)

See screenshot here

标签: angularrxjs

解决方案


Hi to convert an array to a list of items you could use the flatMap operator; the you can work on each item in the subscribe or trasform with map

this.service.getNews().pipe(
    flatMap(x => x)
).subscribe(x => {
    // do something for each item
});

or

this.service.getNews().pipe(
    flatMap(x => x),
    map(x => {
    // transform each item
    })
);

the second is still an Observable


推荐阅读