Understanding RxJS in Our Application
Let’s use our newfound knowledge of RxJS to understand what's going on in our cocktails application.
We'll cover the following
Let’s look at our cocktails application again. In the cocktail.service.ts
, we’re using the http.get()
method to request some data.
this.http.get('https://www.thecocktaildb.com/api/json/v1/1/search.php', {
params: {
s: query,
}
});
The http.get()
method will return an observable. It will emit the values retrieved by the API request. In the app.component.ts
component class file, we’re using the observable by creating an observer with the subscribe()
method.
this.cocktail.search(query).subscribe((response: any) => {
this.drinks = response.drinks;
});
This is how observables are used in action. In our services, we can create observables that can emit data. We can create observers in our components where we’ll need the data.
Improving the request
We can improve how we create requests in our services using pipes and operators. We know that the response from the API will return an object with a property called drinks
. This will represent an array of results based on the query.
Rather than returning the complete response, we’ll return the drinks
arrays. This way, components don’t need to deal with anything else that might be returned.
In the cocktail.service.ts
file, we’ll update the service to the following:
Get hands-on with 1400+ tech skills courses.