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✨
- On your local machine, open Visual Studio Code.
- Go to the File menu and select the Open Folder option.
- Create a new project for this exercise and select this folder.
- Create a new project: open terminal by Ctrl + backtic(`) key then run ng new angular-medium command
Bootstrapping Your Environment✌
- In Visual Studio Code, Ctrl + backtic(`) key press and select the Open in Terminal option.
- 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'?
run this in terminal:👍
npm install @angular/http@latest
Invoke HTTP Get Method
- Within the app folder, open the app.component.ts file.
- 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
Reference
Fake Online REST API for Testing and Prototyping
TypeScript
Angular CLI
Right way to make API calls
Top comments (0)