DEV Community

Bipon Biswas
Bipon Biswas

Posted on

Angular HTTP Client Library

Objective: In this article, you will use the HTTP library in Angular , HTTP GET request, 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 HttpModule module from the @angular/http package:

import {HttpModule} from '@angular/http';
Enter fullscreen mode Exit fullscreen mode

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

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

Note: if run this project then can’t run this project. Get this error:cannot find module '@angular/http'?

run this in terminal:👍

npm install @angular/http@latest
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 Http and Response members (classes) from the @angular/http library module:
import {Http, Response} from '@angular/http';
Enter fullscreen mode Exit fullscreen mode

3.Within the AppComponent class, add a new property named dataItems of type array:

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

4.Create a model named model.ts

export class ItemList{
    public userId: number;
    public id: number;
    public title: string
}
Enter fullscreen mode Exit fullscreen mode

5.Within the AppComponent import model model.ts

import { ItemList } from './model';
Enter fullscreen mode Exit fullscreen mode

6.Within the AppComponent class, add a constructor with a single parameter named http of type Http:

export class AppComponent {
    public dataItems : ItemList[]=[];
    constructor(private http : Http) {
    }
}
Enter fullscreen mode Exit fullscreen mode

7.Add getDummyApiData method into constructor:

constructor(private http : Http) {
    this.getDummyApiData();
}
Enter fullscreen mode Exit fullscreen mode

8.Add getDummyApiData method outside constructor. Also chain an invocation of the toPromise method:

private getDummyApiData(){
      this.http.get('https://jsonplaceholder.typicode.com/posts')
        .toPromise()
    }
Enter fullscreen mode Exit fullscreen mode

9.Add a handler for a successful promise by chaining an invocation of the then method:

private getDummyApiData(){
      this.http.get('https://jsonplaceholder.typicode.com/posts')
        .toPromise()
        .then()
    }
Enter fullscreen mode Exit fullscreen mode

10.Within the then method, invoke the json method of the response object and store the value of it’s dataItems you created earlier:

private getDummyApiData(){
      this.http.get('https://jsonplaceholder.typicode.com/posts')
        .toPromise()
        .then(response => {
          this.dataItems = response.json();
          console.log(this.dataItems)
        })
    }
Enter fullscreen mode Exit fullscreen mode

11.Add a handler for a unsuccessful promise by chaining an invocation of the catch method and adding a semi-colon to complete the statement:

private getDummyApiData(){
      this.http.get('https://jsonplaceholder.typicode.com/posts')
        .toPromise()
        .then(response => {
          this.dataItems = response.json();
          console.log(this.dataItems)
        })
        .catch(error => console.log(error))
    }
Enter fullscreen mode Exit fullscreen mode

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

import {Component} from '@angular/core';
import {Http, Response} from '@angular/http';
import { ItemList } from './model';
@Component({
    selector: 'app',
    templateUrl: './app.component.html',
    styleUrls: './app.component.css',
})
export class AppComponent {
    dataItems:ItemList[]=[];
   constructor(private http: Http) {  
      this.getDummyApiData();
    }
private getDummyApiData(){
      this.http.get('https://jsonplaceholder.typicode.com/posts')
        .toPromise()
        .then(response => {
          this.dataItems = response.json();
          console.log(this.dataItems)
        })
        .catch(error => console.log(error))
    }
}
Enter fullscreen mode Exit fullscreen mode

Render HTTP Response

1.Within the app/views folder, open the app.component.html file.
2.Render the value of the dataItems array type property of the component class by iterate a template expression:

<h1>Demo App</h1>
<hr />
<strong>Example List Item:</strong>
<ul>
    <li *ngFor="let item of dataItems">
        {{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 (0)