Become a member
to unlock all features

Level Up!

Access all courses & lessons on egghead today and lock-in your price for life.


    Render an Observable with the Async Pipe

    John LindquistJohn Lindquist
    2 - 6
    5 - 6

    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.




    Become a Member to view code

    You must be a Member to view code

    Access all courses and lessons, track your progress, gain confidence and expertise.

    Become a Member
    and unlock code for this lesson




    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."

    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.

    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.

    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.

    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.

    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.

    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.

    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.

    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.