Angular 2:很多异步管道和一个订阅
问题描述:
性能和“角度方式”更好:在视图中有多个异步管道,或者组件中有一个订阅者使用onDestroy取消订阅操作?Angular 2:很多异步管道和一个订阅
实施例:
@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
管更有效。在第一个例子中,检查每个更改检测周期的绑定。
答
这是一个很好的问题。 我经常遇到为相同的observable使用多个异步管道的决定,vs订阅OnInit并取消订阅onDestroy。
但是,如果我修改'changeDetection'到'ChangeDetectionStrategy.OnPush'并在订阅块中使用'changeDetector.markForCheck()'? – dakolech
然后它可能与使用异步管道相同。 –