javascript - Angular 2: many Async pipes vs one subscribe - Stack Overflow

What is better for performance and "angular way": have many async pipes in the view or one su

What is better for performance and "angular way": have many async pipes in the view or one subscriber in the ponent with unsubscribe action 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');
  }
}

What is better for performance and "angular way": have many async pipes in the view or one subscriber in the ponent with unsubscribe action 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');
  }
}
Share Improve this question edited Aug 18, 2016 at 9:57 Günter Zöchbauer 659k234 gold badges2.1k silver badges1.6k bronze badges asked Aug 18, 2016 at 9:56 dakolechdakolech 5224 silver badges17 bronze badges 0
Add a ment  | 

2 Answers 2

Reset to default 5

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.

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.

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745399302a4626026.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信