Angular HTTP Client Library
Published: 2020-11-11 11:05:55

---
title:Angular HTTP Client Library
published: true
description: HTTP library in Angular, HTTP GET request, web API request 
tags: 
//cover_image: https://direct_url_to_image.jpg
---

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

To start the port correctly in your desired port use:

```
npm start --port 8000 --open
```
**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';
```

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 { }
```

**Note**: if run this project then can’t run this project. Get this error:[cannot find module '@angular/http'?](https://medium.com/@bipon68/angular-http-client-library-4a305d99e4af)

**run this in terminal**:👍

```
npm install @angular/http@latest
```

**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';
```

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

```
export class AppComponent {
    public dataItems : ItemList[]=[];
}
```

4.Create a model named **model.ts**

```
export class ItemList{
    public userId: number;
    public id: number;
    public title: string
}
```

5.Within the **AppComponent** import model **model.ts**

```
import { ItemList } from './model';
```

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) {
    }
}
```

7.Add **getDummyApiData** method into constructor:

```
constructor(private http : Http) {
    this.getDummyApiData();
}
```

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()
    }
```

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()
    }
```

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)
        })
    }
```

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))
    }
```

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))
    }
}
```
**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>
```

**Output**

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/giwi5rsjzm35w4wl0tx4.png)


[Github](https://github.com/bipon68/angular-medium)
[StackBlitz](https://stackblitz.com/github/bipon68/angular-medium)


**Reference**

[Fake Online REST API for Testing and Prototyping](https://jsonplaceholder.typicode.com/)
[TypeScript](https://scrimba.com/learn/intrototypescript)
[Angular CLI](https://angular.io/cli)
[Right way to make API calls](https://medium.com/javascript-in-plain-english/the-right-way-to-make-api-calls-in-angular-5cc03a62bf43)