![]() |
VOOZH | about |
Most applications obtain data from the backend server. They need to make an HTTP GET request. In this article, we'll look at making an HTTP request and map the result/response in a local array. This array can be used to display or filter the items as we want. The most important thing here is using Observable. Let's quickly look at Observable first.
Observable is important because it helps to manage asynchronous data (such as data coming from a back-end server). So we can think of Observable as an array where items arrive asynchronously over time. With Observable we need a method in our code that will subscribe to this observable. Observable is used by Angular itself including angular event and angular HTTP client service which is why we're covering observable here. Important steps are listed below:
Stored the URL in a variable, album_url. Now we need the HttpClient service to make HTTP GET requests to that URL, so we've to inject it into the constructor. Make sure you import HttpClientModule from @angular/common/http in the corresponding module file.
Notice that, here the data type for Observable is IAlbum list and the return type of the getting method is also IAlbum list. the album is an interface.
For now, just know that this type-casting is necessary because the returned JSON response should be compatible with the type of IAlbum that we are dealing with. Here pipe and tap are related to Observable and are discussed in great detail in a different article.
Now let's create a method in our component code that will subscribe to this Observable.
album-list.component.ts:
This component wants to display the list of all the albums that are just fetched by the HTTP request. Notice local array albums whose type is also IAlbum. See how imported the AlbumService and injected it into the constructor. Created a separate method also but it's recommended to fetch the data within the ngOnInit life cycle hook. Subscribing to the required method of AlbumService (there can be other methods also in the same service). Inside the next block local array, this.albums is populated.
Iterate through that array using the ngFor directive.
album-list.component.html:
Output: