What is better for performance and "angular way": have many async pipes in the view or one subscriber in the component 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');
}
}
Async pipe creationOn the first call to transform, a subscription will be created from the observable we passed in. If our observable emits a new value, the display value ( this. _latestValue ) will be updated. Note, obj is the observable we've passed in, also known as the source observable.
The async pipe subscribes to an Observable or Promise and returns the latest value it has emitted. When a new value is emitted, the async pipe marks the component to be checked for changes. When the component gets destroyed, the async pipe unsubscribes automatically to avoid potential memory leaks.
The pipe method of the Angular Observable is used to chain multiple operators together. We can use the pipe as a standalone method, which helps us to reuse it at multiple places or as an instance method.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With