2016-08-18 71 views
10

性能和「角度方式」更好:在視圖中有多個異步管道,或者組件中有一個訂閱者使用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'); 
    } 
} 

回答

3

使用,因爲角被通知關於變化| async管更有效。在第一個例子中,檢查每個更改檢測週期的綁定。

+0

但是,如果我修改'changeDetection'到'ChangeDetectionStrategy.OnPush'並在訂閱塊中使用'changeDetector.markForCheck()'? – dakolech

+0

然後它可能與使用異步管道相同。 –

0

這是一個很好的問題。 我經常遇到爲相同的observable使用多個異步管道的決定,vs訂閱OnInit並取消訂閱onDestroy。