How to retrieve data using HTTP with Observables in AngularJS ?

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 that is why we’re covering observable here.

Important steps are listed below:

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

Create a service: album.service.ts

filter_none

edit
close

play_arrow

link
brightness_4
code

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 =
  constructor(private _http: HttpClient) {}
}

chevron_right


Stored the URL in a variable, album_url. Now we need HttpClient service to make HTTP GET request 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.



filter_none

edit
close

play_arrow

link
brightness_4
code

@NgModule({
  imports: [ BrowserModule, 
       FormsModule, HttpClientModule ],
  declarations: [ ... ],
  providers: [ AlbumService ],
  bootstrap:    [ ...]
})
export class AppModule { }

chevron_right


Now create a method getAllAlbums():

filter_none

edit
close

play_arrow

link
brightness_4
code

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 =
  constructor(private _http: HttpClient) {}
  getAllAlbums(): Observable<IAlbum []> {
    return this._http.get<IAlbum []>(this.albums_url)
      .pipe(
        tap(data => 
        console.log('All: ' + JSON.stringify(data)))
      );
  }
}

chevron_right


Notice that, here the data type for Observable is IAlbum list and the return type of get method is also IAlbum list. IAlbum is an interface.

filter_none

edit
close

play_arrow

link
brightness_4
code

export interface IAlbum {
  albumId : number;
  id : number;
  title : string;
  url : string;
  thumbnailUrl    : string;
}

chevron_right


For now, just know that this type-casting is necessary because the returned JSON response should be compatible with the type of album that we are dealing with. Here pipe and tap are related to Observable and are discussed in great detail in a different article.

Inject this service and store the response in a local array: Now let’s create a method in our component code that will subscribe to this Observable.

album-list.component.ts

filter_none

edit
close

play_arrow

link
brightness_4
code

import { Component, OnInit } from '@angular/core';
import { IAlbum } from '../model/album';
import { AlbumService } from '../service/album.service';
  
@Component({
  selector: 'album-list',
  templateUrl: './album-list.component.html',
  styleUrls: ['album-list.component.css']
})
export class AlbumListComponent implements OnInit {
  albums: IAlbum[] =[];
  constructor(private _albumService: AlbumService) { }
  ngOnInit() {
    this._albumService.getAllAlbums().subscribe({
      next: albums =>{
        this.albums=albums
      }
    })
  }
}

chevron_right


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 ngOnInit life cycle hook. Subscribing to the required method of AlbumService (there can be other methods also in the same service). Inside next block local array this.albums is populated.

Displaying the list in template/view: Iterate through that array using ngFor directive.

album-list.component.html

filter_none

edit
close

play_arrow

link
brightness_4
code

<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>

chevron_right


Output:




My Personal Notes arrow_drop_up

A Computer Science student

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.