Angular 角度5-什么';将组件变量作为可观察类型的好处是什么?
我是Angular 6的新手,在下面的链接中阅读了关于Angular 角度5-什么';将组件变量作为可观察类型的好处是什么?,angular,typescript,http,observable,Angular,Typescript,Http,Observable,我是Angular 6的新手,在下面的链接中阅读了关于http过程的内容: 我注意到在组件中,heroes数组的类型是可观察的 我不确定组件内部是否总是需要这样 在我自己的代码中,我能够绑定一个不可见的数据: export class UserInfoComponent implements OnInit { data: object; constructor(private userInfoService: UserInfoService) {} ngOnIni
http
过程的内容:
我注意到在组件中,heroes数组的类型是可观察的
我不确定组件内部是否总是需要这样
在我自己的代码中,我能够绑定一个不可见的数据:
export class UserInfoComponent implements OnInit {
data: object;
constructor(private userInfoService: UserInfoService) {}
ngOnInit() {
this.userInfoService
.getEmployeeInfo()
.subscribe((response) => {
this.data = response;
});
}
}
我不确定最佳实践是什么,或者每种方法的优缺点是什么。在这种情况下,您可以将变量作为可观察变量-您有一些
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);
}
作为类变量可观察不是强制性的。 Observable基于使用流的概念,其中订阅者订阅该流发出的任何内容
然而,在这种情况下,默认情况下,这里的HTTP响应是一个可观察的响应,您可以订阅并进一步使用此响应流发出的任何内容 这就是为什么
angular
成为反应式框架的原因。我来自AngularJS 1.5,1.5使用承诺。我仍然在思考v5中的新http方法。