【问题标题】:Angular 5 - what's the benefit in having component variables as type Observable?Angular 5 - 将组件变量作为 Observable 类型有什么好处?
【发布时间】:2018-08-27 21:41:48
【问题描述】:

我是 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;
            });
    }
}

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

【问题讨论】:

  • 这就是使angular 成为reactive framework 的原因。
  • 我来自 AngularJS 1.5 和 1.5 使用承诺。我仍在思考 v5 中的新 http 方法。

标签: angular typescript http observable


【解决方案1】:

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

【讨论】:

    【解决方案2】:

    Observable 作为类变量不是强制性的。 Observable 基于使用流的概念,其中订阅者订阅该流发出的任何内容。

    然而,在这种情况下,默认情况下这里的 HTTP 响应是一个可观察的对象,您订阅并进一步使用此响应流发出的任何内容。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-09-12
      • 1970-01-01
      • 1970-01-01
      • 2018-09-04
      • 1970-01-01
      • 2018-07-24
      • 1970-01-01
      • 2017-06-08
      相关资源
      最近更新 更多