什么对性能和“Angular 方式”更好:在 View 中有许多异步管道或在组件中有一个订阅者在 Destroy 上有取消订阅操作?
例子:
@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');
}
}
最佳答案
使用| async
管道更高效,因为 Angular 会收到有关更改的通知。对于第一个示例,每个更改检测周期都会检查绑定(bind)。
关于javascript - Angular 2 : many Async pipes vs one subscribe,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39015185/