简体   繁体   中英

How to async pipe an observable in Angular

I have a service that has some asynchronous stuff to do, how can I postpone a data binding render until the service has done its asynchronous work?

this.sessionService.onSessionChange().subscribe(function(session) {
    console.log(session);
    self.user = session.user;
});

Service:

onSessionChange(): Observable<Session> {
    return this.sessionObservable.asObservable();
}

The user is undefined because the session isn't ready yet:

<h4>Hi {{user.name}}.</h4>

How can I use a pipe with my onSessionChange observable?

In Angular4, a common idiom is to use the new as keyword as follows:

<ng-container *ngIf="session$ | async as session">
                                 <!-- ^^^^^^^^^^  "as" keyword -->
  <h4>Hi {{session.user.name}}</h4>
</ng-container>

This is even more useful if you are going to use session in more than one place in your template.

<ng-container> is a place to hang *ngIf or *ngFor without adding more nodes to the DOM.

As @Sajeetharan answered, you can use safe navigation operator to avoid undefined error thrown from template.

Just as you stated at your question's header, you can use Async Pipe to subscribe/unsubscribe to Observable automatically.

Step1: expose the Observable at your component:

// expose Observable in order to access at template
user$: any;
constructor(private sessionService: SessionService) {
  this.user$ = this.sessionService.onSessionChange();
}

Step2: use Async Pipe at your template to subscribe to the created Observable

<h4>Hi {{(user$ | async)?.user.name}}.</h4>

Working DEMO

您也可以使用safe navigation operator来处理这种情况,

<h4>Hi {{user?.name}}.</h4>

Use the pluck operator to have an async property:

At the component:

this.userName$ = this.sessionService.onSessionChange().pluck('user', 'name')

At the template:

<h4>{{ userName$ | async }}</h4>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM