Reputation: 296
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 :)
Upvotes: 3
Views: 5476
Reputation: 1
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));
Upvotes: 0
Reputation: 1860
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
Upvotes: 6
Reputation: 710
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 New
s.
Upvotes: 0