angular - Angular 5 - 将组件变量作为 Observable 类型有什么好处?
问题描述
我是Angular 6的新手,并且一直在阅读http
以下链接中的流程:
https://angular.io/tutorial/toh-pt6#create-herosearchcomponent
我注意到在组件中,英雄数组的类型是Observable
.
我不确定组件内部是否总是需要这种情况。
在我自己的代码中,我能够数据绑定一个不可观察的:
export class UserInfoComponent implements OnInit {
data: object;
constructor(private userInfoService: UserInfoService) {}
ngOnInit() {
this.userInfoService
.getEmployeeInfo()
.subscribe((response) => {
this.data = response;
});
}
}
我不确定最佳实践是什么,或者每种方法的优缺点是什么。
解决方案
在这种情况下,您可以将变量设置为 Observable - 您有一些RxJS
运算符链接,并且在您的代码中您希望多次订阅链接流。因此,为了不要每次都组合这些运算符,您可以将它们保存在属性中并只添加一个.susbcribe
。
this.heroes$ = this.searchTerms.pipe(
// wait 300ms after each keystroke before considering the term
debounceTime(300),
// ignore new term if same as previous term
distinctUntilChanged(),
// switch to new search observable each time the term changes
switchMap((term: string) => this.heroService.searchHeroes(term)),
);
inOneMethod() {
this.heroes$.subscribe(data => this.first = data);
}
inAnotherMethod() {
this.heroes.subscribe(data => this.second = data);
}
推荐阅读
- css - 在锚链接中包含 CSS 计数器?
- java - 如何在不使用任何库或集合的情况下从数组中删除所有重复元素
- batch-file - 为什么我的批处理变量设置为空格?
- python - 熊猫:无法删除第二列
- reactjs - 在 React 中,如何显示使用数据库中特定项目的数据的页面
- javascript - 我可以使用 getatribute 将样式更改为无吗?
- python - jinja2.exceptions.UndefinedError:“消息”未定义
- c++11 - 在此示例中,让 `std::ostreambuf_iterator` 写入字符串而不是 `std::cout`
- javascript - 带有 SSML 的 SpeechSynthesisUtterance 是童话吗?
- javascript - Gatsby/Contentful 将数据从一个组件传递到另一个组件