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