I have a resolver that fetches data from a service and passes that Observable object to the component which subscribes and implements the resolver.
resolve (route: ActivatedRouteSnapshot): Observable<NewsAPIArticle[]> {
return this.newsAPIService.getNewsAPIArticles()
.pipe(
catchError(error => {
this.alertify.error('Problem retrieving news');
return of(null);
}),
take(5)
);
}
In the ngOnInit of the component, I get the data, save it to a local array, and console log the array.
ngOnInit() {
this.router.data.subscribe(data => {
this.articles = data['news']['articles'];
console.log(this.articles);
this.language = 'en';
});
}
However, instead of console logging 5 things the resolver should "take" from the observable as I understand it, the array comes back with 20 objects. What am I doing wrong in the take rxjs operator? I don't want all 20 responses, only maybe 5.

take(5) means it will take 5 items from the stream. The array is a single item in the stream as the observable is of type NewsAPIArticle[]. If the observable was of type NewsAPIArticle, and the stream emitted multiple articles, take(5) would behave as you expect, but as it is, the service you call emits all articles at once.
You should use map with slice,
.pipe(...
map(x => x.slice(0,5))
)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With