angular - 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.
解决方案
take(5)
意味着它将从流中获取 5 个项目。数组是流中的单个项目,因为 observable 的类型是NewsAPIArticle[]
。如果 observable 的类型是NewsAPIArticle
,并且流发出了多篇文章,take(5)
那么它的行为会如您所愿,但实际上,您调用的服务会立即发出所有文章。
推荐阅读
- node.js - PM2下运行的Node JS进程及文件权限
- android - 如何启动用 Rust 编写的 Android 后台服务?
- javascript - 努力循环遍历一组对象
- python - 类型错误:book() 缺少 1 个必需的位置参数:'book_id'
- html - 无法打开其他页面
- html - ELEMENTOR 中的 CSS 和 HTML 用于 1 框标题下拉菜单
- json - SQL 服务器:使用 JSON_QUERY 选择所有 json 数组元素
- c# - 使用 System.Text.Json 序列化 JSON 时动态忽略密封类上的属性
- go - 为什么互斥锁最终会出现线程正在休眠的错误?
- python - 背景减法器python opencv(去除颗粒)