Subscribing and Unsubscribing from Observables
Let's explore how we can subscribe and unsubscribe to the observables.
We'll cover the following...
Subscribing to Observables
As we saw in the Dependency Injection, Services, and HttpClient chapter, when we implemented one of the HttpClient methods, it returned an Observable, but it wasn’t until we called the Subscribe method of the Observable that it actually ran.
HttpClient’s get()
method
When we made a request to get some data using the HttpClient’s get()
method, the data wasn’t loaded until we called the Subscribe method at the component level. We set up the HttpClient get()
method call in our service and returned the Observable that the get()
method returns. Then, in the component, we called the Subscribe of that returned Observable.
In this Subscribe method, we pass in the Observer. In this example, we are returning the Observable that the get()
method creates for us:
const externalAPI = 'example.com/data';
loadSomeData() {
return this.httpClient.get(externalAPI)
}
Then in the Component, we call the Subscribe method of this Observable:
this.service.loadSomeData().subscribe((data) => {
console.log(data);
})
This is a common pattern to use when working with Observables, but in the preceding code, we’re not defining this “subscribe” method. We’re just calling it. How is that possible? Well, we know that the get()
method of the HttpClient returns an Object, which is an Observable. If we look at the official API documentation, we can see that it returns an ...