Angular 2:许多异步管道与一个订阅

时间:2016-08-18 09:56:47

标签: javascript angular typescript rxjs

对于性能有什么好处,"有角度的方式":在视图中有多个异步管道,或者组件中的一个用户有取消订阅动作onDestroy?

示例:

@Component({
  template: `<div> {{ post.title }} {{ post.author.name }} {{ post.category.name }} </div>`
  ...
  })
class AppComponent {
  public post: Post;
  public postSubscription;

  ngOnInit() {
    postSubscription = someObservable.subscribe((post) => {
      this.post = post;
    })
  }

 ngOnDestroy() {
    postSubscription.unsubscribe();
 }
}

@Component({
  template: `<div> {{ postTitle | async }} {{ postAuthorName | async }} {{ postCategoryName | async }} </div>`
  ...
  })
class AppComponent {
  public postTitle: Observable<string>;
  public postAuthorName: Observable<string>;
  public postCategoryName: Observable<string>;

  ngOnInit() {
    this.postTitle = someObservable.pluck('title');
    this.postAuthorName = someObservable.pluck('author', 'name');
    this.postCategoryName = someObservable.pluck('category', 'name');
  }
}

2 个答案:

答案 0 :(得分:5)

使用| async管道更有效,因为Angular会收到有关更改的通知。在第一个示例中,每个更改检测周期都会检查绑定。

答案 1 :(得分:0)

这是一个很好的问题。 我经常遇到为同一个observable使用多个异步管道的决定,而不是订阅OnInit和取消订阅onDestroy。