Welcome to part-8 of Angular Basics series. In this part also, we will learn about Observables. The starting point can be taken from here.
It’s a simple project, which already have an inbuilt observable.
We will build our own observables from ground up to learn more about Observables. They are given to us in angular by a package called rxjs. We are going to create our own observable in home.component.ts file.
Here, we are using the interval from rxjs, which is logging count after every second. In obsevables, we have to subscribe to it. Also notice that we are unsubscribing to it and adding it to the ngOnDestroy, so that it will stop once we are done.
In localhost, we will see an increasing counter in the home component and it will stop, once we move away from it.
We will now build a real custom observable. Here, we are using Observable from rxjs and using setInterval to increase the count.
After that we are again subscribing to it and console logging the data.
We will see the same behavior in localhost. As we can see that emitting new data is the most important thing that observables do, but they also throw errors.
In home.component.ts file, we are throwing an error if count is greater then 4. Now, in the subscribe method, we are console logging the error.
When an error is thrown, it cancels the observable and it dies.
But in most cases the Observable will be completed, as in the case of http request. We can also throw an observer.complete() and catch that in the subscription.
Now, after count of 2, we will see the Complete message.
We can add operators also to add functionality before our observable starts. There are many operators and we will use filter and map and we are using them in our home.component.ts file.
Now, because of the filter our round will start with 2 and then complete.
This completes our post on Observables. You can find the code for the same in this github repo.