首页 > 解决方案 > RxJS take operator not working with Angular app

问题描述

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

标签: angularrxjs

解决方案


take(5)意味着它将从流中获取 5 个项目。数组是流中的单个项目,因为 observable 的类型是NewsAPIArticle[]。如果 observable 的类型是NewsAPIArticle,并且流发出了多篇文章,take(5)那么它的行为会如您所愿,但实际上,您调用的服务会立即发出所有文章。


推荐阅读