Displaying the List in Template/View

Iterate through that array using the ngFor directive.

album-list.component.html:

HTML




<h1>
    Albums list!
</h1>
<ul>
    <li *ngFor="let album of albums">
        <p>Uploaded by User no. : {{album.id}}</p>
        <p>Album name: {{album.title}}</p>
    </li>
</ul>


Output:

 



How to Retrieve Data using HTTP with Observables in Angular ?

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:

  • Create a service using the command: ng g s album. Here we’ll create a class AlbumService.
  • In AlbumService class create a method, say getAllAlbums(), which will make HTTP GET request using Observable.
  • Inject this service into the constructor of any component that wants to use these methods. For example- AlbumListComponent.
  • Create a method or use an angular life cycle hook in AlbumListComponent class that will subscribe to the observable and then harvest the received response.

Similar Reads

Create a service: album.service.ts

Javascript import { Injectable } from "@angular/core"; import { HttpClient } from "@angular/common/http"; import { Observable } from "rxjs"; import { catchError, tap, map } from "rxjs/operators"; import { IAlbum } from "../model/album";   @Injectable({     providedIn: "root", }) export class AlbumService {     albums_url: string =         "https://jsonplaceholder.typicode.com/albums";     constructor(private _http: HttpClient) { } }...

Create a new getAllAlbums() Method

...

Inject This Service and Store the Response in a Local Array

...

Displaying the List in Template/View

Javascript import { Injectable } from "@angular/core"; import { HttpClient } from "@angular/common/http"; import { Observable } from "rxjs"; import { catchError, tap, map } from "rxjs/operators"; import { IAlbum } from "../model/album";   @Injectable({     providedIn: "root", }) export class AlbumService {     albums_url: string =         "https://jsonplaceholder.typicode.com/albums";     constructor(private _http: HttpClient) { }     getAllAlbums(): Observable {         return this._http             .get < IAlbum[] > (this.albums_url)                 .pipe(tap((data) => console.log("All: "                     + JSON.stringify(data))));     } }...