RxJS operator with array

Viewed 2400

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

3 Answers

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

Well, the map operator in rxjs's pipe is operating on the stream of async data, in other words, the Observable.

So here, you have an Observable<News[]> which means a stream of New[]. that means your this.newsService.getNews().pipe(map(news => {});'s news is an array of News.

If you would like to transform each item inside pipe() you can use:

this.getNews()
        .pipe(
            switchMap(newsList => from(newsList)
                .pipe(
                    map(news => {
                        // Do something with each item
                        console.log(news);

                        return news;
                    })
                )
            ),
            // Set back to array
            reduce((curr: NewsData[], next: NewsData) => [...curr, next], []),
        )
        .subscribe(data => console.log(data));
Related