How to use Observable with Async pipe inside Angular2 click function How to use Observable with Async pipe inside Angular2 click function angular angular

How to use Observable with Async pipe inside Angular2 click function


In your template (click)="openDeckOnBrowser(course.deckUrl)" is evaluated as soon as the template is parsed. You do not use the async pipe here, hence the deckUrl is empty. You can fix this by adding a second async pipe:

<p>{{(course|async)?.description}}</p><button ... (click)="openDeckOnBrowser((course|async).deckUrl)">...</button>

However, this is not nice as two subscriptions will be created.

A (better) alternative:

The official docs on the AsyncPipe always use *ngFor to output a list of items and not *ngIf to output a single item. The reason is simple: the *ngIf directive does not allow any assignments. But we can work around this limitation:

The template looks as follows:

<div *ngFor="let course of course$|async">    <p>Course: {{course?.name}}</p>    <p>Url: {{course?.url}}</p></div>

And in the component, we'll just map the course to a list of a single course:

this.getCourse().map(c=>[c]);

See working Demo in Plunker


Just subscribe to the observable in your code, and store the course itself in the component:

this.af.database.object('/bbwLocations/courses/' + courseId)    .subscribe(course => this.course = course); 

Then in you view:

<p>{{ course?.description }}</p><button ion-button dark full large (click)="openDeckOnBrowser(course?.deckUrl)">

(although I would probably use ng-if and only show the description and the button once the course is available)