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

时间:2021-07-02 09:57:52

What is better for performance and "angular way": have many async pipes in the view or one subscriber in the component with unsubscribe action onDestroy?

对性能和“角度方式”更好的是什么:视图中有许多异步管道,组件中有一个订阅服务器,使用unsubscribe操作onDestroy?

Example:

例子:

@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();
 }
}

or

@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 个解决方案

#1


3  

Using the | async pipe is more efficient because Angular gets notified about changes. With the first example the bindings are checked each change detection cycle.

使用|异步管道更有效,因为角将得到关于更改的通知。使用第一个示例,对每个变更检测周期检查绑定。

#2


0  

This is a great question. I often came across the decision of use multiple async pipes for the same observable, vs subscribing OnInit and unsubscribing onDestroy.

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

#1


3  

Using the | async pipe is more efficient because Angular gets notified about changes. With the first example the bindings are checked each change detection cycle.

使用|异步管道更有效,因为角将得到关于更改的通知。使用第一个示例,对每个变更检测周期检查绑定。

#2


0  

This is a great question. I often came across the decision of use multiple async pipes for the same observable, vs subscribing OnInit and unsubscribing onDestroy.

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