Observables and Subscriptions In Angular
One of the most important concepts to understand in Angular is what Observables are, how they work, and how to use them in your code. The Angular website has some extensive documentation on Observables, but in this blog I plan to cover the basics of its usage and what you need to know to begin working with observables. As someone fairly new to Angular, it quickly became apparent that understanding this data flow early would make my life easier.
So what are Observables? At a high level Observables are a means to transmit information or events between the different parts of an application. Observables help you pass data asynchronously and are great for calling on an API or service when getting a response could take an unknown amount of time. An Observable provides a steady data stream to relay our information.
In turn, a Subscription is how we access this data! An Observer will subscribe or ‘listen’ to this Observable and have access to the data provided as well as any changes that take place within the stream. An Observable is going to provide information when an Observer subscribes to it, and it will continue to do so until it is Unsubscribed from. For the sake of continuity, I am going to mainly use the language provided in the Angular documentation, which calls the object that provides the data a subject and the any object that receives the data an observer. The observer can also be called a consumer, because it consumes the data of the Observable
For example, if you are a developer on the job hunt, you may subscribe to websites like indeed or Linkedin to receive messages about the latest positions available. You get emails whenever a new position that matches your description is available. However, when you finally find that perfect job, you can unsubscribe to these websites and you (eventually) stop receiving these emails. Linkedin acts as the Observable, and to access the data stream, or emails, you must subscribe to the Observable.
Overview examples are great, but we are more interested in utilizing this feature practically in our applications. I will demonstrate how to use Observables and subscribe to them in Angular.
How To Create An Observable
For the purpose of this blog I have created an Angular application with the
ng new application-name
command. I will not go into detail here on how to set up an Angular application, but I will make the code available and go over what you need to do to create an observable within a boiler-plate Angular application.
In our app.component.ts component, lets add the following code:
Here, we are creating local variable ‘observable’ and assigning it to an Observable by calling the create method on the Observable object imported from rxjs. We then pass the create method an observer function which affects our stream of data. You can see on line 13 when the Observable is first subscribed to, it returns a string ‘Begin subscription to observer’. To imitate the time delay of an HTTP request, I have written two timeout functions, one that returns another string 3 seconds later, and one that calls the complete() method on the observer, ending the stream.
To subscribe to this observable, we can call the .subscribe() method on the observable object inside of our ngOnInit() function. This means that as soon as our component is initialized, we begin subscribing to the Observable. We can either hook into the data provided by the observable, any errors it may throw, or when it is completed. below is a demonstration of attaching to all three.
If we start our development server with the
command and navigate to localhost:4200, we can see the result of our subscription on the console.
Note that as you might have predicted ‘Initialization’ is logged right after ‘Begin subscription…’. However, the ‘Update in data’ log and the ‘Subscription finished’ log appear after. This is because we are observing an asynchronous Observable. As I mentioned earlier, one of the main uses for Observables is handling asynchronous data flow, and here we have demonstrated that.
To demonstrate the ability to log an error on our Observable, let’s change the observable object slightly to produce an error instead of completing. If we comment out our observer.complete() setTimeout and write a new timeout below it that looks like this:
We can see our subscription on line 31 caught the error, and will log the message.
A More Practical Example
Now that we know how observables work and how to create them, we can create one that is a little more useful. The Angular documentation for Observables demonstrates how to display the current time, but it is not an in depth or entirely clear demonstration for those new to the concept, so I will expand on the idea.
We can create a new component to get the time with the following command:
ng generate component get-the-time
Inside of the newly generate get-the-time.component.ts file, let us change the code. We will create an Observable that gets the current time every second as in the Angular documentation, but we will also assign it to a variable that we will update. On initialization of the component, we will subscribe to our time Observable and use the data from the stream to update our currentTime variable.
And we can show the time by simply adding this to our new html component
and changing our original app.component.html to only the following line of code
In the browser, we will now see a clock that updates the time every second!
This has been only a high level overview on what observables are and what we can do with subscriptions to them. Usually in projects, you will be subscribing to receive data from API’s and will expect it to be received asynchronously. The beautiful thing about Observables as opposed to Promises, is that Observables can be thought of as ‘pipes’ of data that stay open until closed, errored, or finished, providing a stream of values.. Promises, however, provide a single value.
I highly recommend practicing by creating some Observables yourself and utilizing them in your own projects. Think of scenarios where you would need to asynchronously fetch a stream of data, like updating the weather, or filling in a list of To Do items. I hope this blog will help any Angular beginners trying to understand some of the core concepts. Feel free to leave some feedback or ask any questions, and as always, Happy Coding!
Contribute to AidanMcB/observable-blog development by creating an account on GitHub.
Angular is a platform for building mobile and desktop web applications. Join the community of millions of developers…