Render an Observable with the Async Pipe

John Lindquist
InstructorJohn Lindquist
Share this video with your friends

Social Share Links

Send Tweet

Angular templates use a special Async pipe to be able to render out Observables. This lesson covers the syntax used to create an Observable in Angular and then to render it out in the template.

https://github.com/johnlindquist/rxjs-in-angular2/tree/11aa4c29a4536dad0ef26b78d8f7f503e4372f74/src

[00:00] We're just starting with a "Hello World" Angular 2 app, where we bootstrap an app, and this app is exported from here with a field of message, says "Hello World," and then render it out in the template, so it gives us "Hello World."

[00:12] To start with our clock, we'll create a field of clock, assign that to Observable. We need to import Observable, which we'll do from RxJS/Observable. We want to import Observable.

[00:28] We can do Observable.interval. We'll say this is an interval of one second. If I try and run this right now...I'll refresh, you can see I'll get an error saying that interval down here is not a function.

[00:43] What that means is you need to import every method on Observable by itself, so we'll import interval. When I hit Save and run this again, you'll see that error will go away.

[00:55] If you wanted to, you could just import all of RxJS by just importing Rx and you can see we won't have an error here. But that imports the whole shebang versus just importing one method off of it, and RxJS can be a pretty big library if you try to and imported everything.

[01:11] To use our Observable, just our clock, we'll drop it into our template, just say clock, we'll hit Save and refresh, and you might expect to get the clock. But what we get is an object. That's because the Observable we get back is an object.

[01:27] That object pushes out values asynchronously so we have a pipe called async which can handle that. If we just say pipe and then the word async and we refresh. Now you can see we get zero, one, two, three, every one second, it's incrementing.

[01:45] What's happening here with this async pipe is that if we do the same thing just in the constructor, if we were to say, this.clock.subscribe, as you would with any other Observable, and then just log out the result, console log and bind it to the console. You'd see that in the console now, it'll log out those same zero, one, two, three.

[02:08] That's because async and the template is simply doing a subscribe on this Observable and it's rendering out this value, whereas, compared to here with the subscribe it's just logging it out to the console.