javascript - Angular 2:多個 Async pipe 與單個 subscribe
對於效能和「Angular 方式」來說哪個更好:在視圖中使用很多 async 管道,還是在組件中使用一個訂閱者,並在 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');
}
}
答案#1
使用 | async 管道更有效率,因為 Angular 會收到變更通知。使用第一個範例時,綁定在每次變更檢測循環中都會被檢查。
答案#2
這是一個很好的問題。我經常遇到是否對同一個 observable 使用多個 async pipe,或者在 OnInit 訂閱並在 onDestroy 退訂的抉擇。