首页 > 解决方案 > 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;
            });
    }
}

我不确定最佳实践是什么,或者每种方法的优缺点是什么。

标签: angulartypescripthttpobservable

解决方案


在这种情况下,您可以将变量设置为 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);
}

推荐阅读