DEV Community

Bipon Biswas
Bipon Biswas

Posted on • Edited on

Angular RxJS Observable Class

Objective: In this article, you will use the HTTP library in Angular in conjunction with RxJS, HTTP GET request, RxJS Observables to handle an asynchronous web API request.

Pre-requisite Prior to completing this article, you should have already installed all pre-requisite tooling including: Visual Studio Code, Node Package Manager (NPM), Node, Angular CLI.

Setup

  1. On your local machine, open Visual Studio Code.
  2. Go to the File menu and select the Open Folder option.
  3. Create a new project for this exercise and select this folder.
  4. Create a new project: open terminal by Ctrl + backtic(`) key then run ng new angular-medium command

Bootstrapping Your Environment

  1. In Visual Studio Code, Ctrl + backtic(`) key press and select the Open in Terminal option.
  2. Run the angular-medium project using npm:
npm start
Enter fullscreen mode Exit fullscreen mode

To start the port correctly in your desired port use:

npm start --port 8000 --open
Enter fullscreen mode Exit fullscreen mode

Add the Http Module

  1. Within the app folder, open the app.module.ts file.
  2. Add an import statement to the top of your file that imports the HttpClientModule module from the @angular/common/http package:
import {HttpClientModule} from '@angular/common/http';
Enter fullscreen mode Exit fullscreen mode

3.Update the NgModule decorator by adding the HttpClientModule module to the values in the import array property of the NgModule decorator:

@NgModule({
    imports:      [ 
        BrowserModule,
        HttpClientModule
    ],
    declarations: [ 
        AppComponent
    ],
    bootstrap: [ AppComponent ]
})
export class AppModule { }
Enter fullscreen mode Exit fullscreen mode

Invoke HTTP Get Method

  1. Within the app folder, open the app.component.ts file.
  2. Add a new import statement to import the HttpClient from the @angular/common/http library module:
import { HttpClient } from '@angular/common/http';
Enter fullscreen mode Exit fullscreen mode

3.Add a new import statement to import the Observable member (class) from the rxjs library module:

import {Observable} from 'rxjs';
Enter fullscreen mode Exit fullscreen mode

4.Within the AppComponent class, add a new property named dataItems of type string:

export class AppComponent {
    dataItems2:ItemList[]=[];
}
Enter fullscreen mode Exit fullscreen mode

5.Within the AppComponent class, add a new empty constructor:

export class AppComponent {
    dataItems2:ItemList[]=[];
    constructor() {
    }
}
Enter fullscreen mode Exit fullscreen mode

6.Add a model named ItemList. And import into app.component.ts file

import { ItemList } from './model';
export class ItemList{
    public userId: number;
    public id: number;
    public title: string
}
Enter fullscreen mode Exit fullscreen mode

7.Update the constructor by adding a parameter of type httpclient:

constructor(private httpclient : HttpClient) {
}
Enter fullscreen mode Exit fullscreen mode

8.Within the AppComponent class, add a new method named getDummyApiData2:

export class AppComponent {
    dataItems2:ItemList[]=[];
    constructor(private httpclient : HttpClient) { ... }
    private getDummyApiData2() {
    }
}
Enter fullscreen mode Exit fullscreen mode

9.Update the getDummyApiData2 method signature by adding return type of Observable:

private getDummyApiData2() : Observable<ItemList[]> {
}
Enter fullscreen mode Exit fullscreen mode

10.Within the getDummyApiData2 method, return the result of invoking the get method on the httpclient private variable:

private getbiponIPAddress() : Observable<ItemList[]> {
    return this.httpclient.get<ItemList[]>('https://jsonplaceholder.typicode.com/posts');
}
Enter fullscreen mode Exit fullscreen mode

11.Returning to the empty constructor, add a line of code to invoke the getDummyApiData2 method:

constructor(private httpclient : HttpClient) {
    this.getDummyApiData2()
}
Enter fullscreen mode Exit fullscreen mode

12.Subscribe to the data being available by invoking the subscribe method:

constructor(private httpclient : HttpClient) {
    this.getDummyApiData2()
      .subscribe(res => {
         this.dataItems2 = res;
    });
}
Enter fullscreen mode Exit fullscreen mode

13.Update the subscribe method by adding an inline anonymous function to get the result of the IP Address request and save it to the dataItems2 property in the AppComponent class:

constructor(private httpclient : HttpClient) {
    this.getDummyApiData2()
      .subscribe(res => {
         this.dataItems2 = res;
    });
}
Enter fullscreen mode Exit fullscreen mode

14.Your final app.component.ts class should now look like this:👀

import {Component} from '@angular/core';
import { HttpClient } from '@angular/common/http';
import {Observable} from 'rxjs';
@Component({
    selector: 'app',
    templateUrl: './app.component.html',
    styleUrls: './app.component.css',
})
export class AppComponent {
    dataItems2:ItemList[]=[];
constructor(private httpclient : HttpClient) {
    this.getDummyApiData2()
      .subscribe(res => {
         this.dataItems2 = res;
    });
  }
    private getDummyApiData2() : Observable<ItemList[]> {
     return this.httpclient.get<ItemList[]>('https://jsonplaceholder.typicode.com/posts');
    }
}
Enter fullscreen mode Exit fullscreen mode

Another way

Just restructure for smarter way to data access.

app.component.ts

import { SampleService } from './sample.service';
dataItems:ItemList[]=[];
constructor(
      private sampleService:SampleService, 
      private httpclient: HttpClient) {  
        this.getDummyApiData();
    }
private getDummyApiData(){
      this.sampleService.getDataList().subscribe(data=>{
      this.dataItems=data;
})
Enter fullscreen mode Exit fullscreen mode

sample.service.ts file

getDataList():Observable<ItemList[]>{
    return this.http.get<ItemList[]('https://jsonplaceholder.typicode.com/posts');
  }
Enter fullscreen mode Exit fullscreen mode

app.component.html file

<ul>
    <li *ngFor="let item of dataItems">
        {{item.title}}
    </li> 
</ul>
Enter fullscreen mode Exit fullscreen mode

Render HTTP Response

  1. Within the app folder, open the app.component.html file.
  2. Render the value of the dataItems2 property iterate by adding *ngFor directive and a template expression:
<h1>Dummy App</h1>
<strong> Example List Item::</strong>
<ul>
    <li *ngFor="let item of dataItems2">
        {{item.title}}
    </li> 
</ul>
Enter fullscreen mode Exit fullscreen mode

Output

Alt Text

Github
StackBlitz

Reference

Fake Online REST API for Testing and Prototyping
TypeScript
Angular CLI
Right way to make API calls

Top comments (3)

Collapse
 
gabrielepiaggesi profile image
Gabri • Edited

Cool, but I prefer async/await method to handle async rest request.
With a Server service that makes requests with standard promise resolve/reject, and on Component's ts file just use await this.serverService.get....

Collapse
 
alfredosalzillo profile image
Alfredo Salzillo

Please add the tag typescript to the codeblocks.

Collapse
 
bipon68 profile image
Bipon Biswas

Thanks.