Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

RxJS take operator not working with Angular app

Tags:

angular

rxjs

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.

enter image description here

like image 854
J.G.Sable Avatar asked Apr 21 '26 02:04

J.G.Sable


2 Answers

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.

like image 124
Andy Lamb Avatar answered Apr 23 '26 16:04

Andy Lamb


You should use map with slice,

 .pipe(...
   map(x => x.slice(0,5))
 ) 
like image 32
ABOS Avatar answered Apr 23 '26 15:04

ABOS