Work with REST API Service in Angular — TypeScript
Today, front-end applications use the Application Programming Interface (API) to communicate with back-end services with a REpresentational State Transfer (REST) based on HTTP protocol architecture. In Angular, we can use HttpClient module to make it happen. So, let’s try!
Create New Angular Project
Angular provides a Progressive Web App architecture, which means that an application made in Angular gives us an modern web app experience with high performance. Angular has Command Line tools (CLI) to build and deploy Apps faster than ever before. To use this CLI, we need to install Node.js first and then install Angular CLI with this command :
npm install -g @angular/cli
Now, you can create new Angular project with zero-step installation with their CLI like this :
ng new AngularAPI
Open new Angular project folder :
cd AngularAPI
Angular can be rendered in Node.js servers by giving the output in HTML-CSS format using this command :
ng serve
You can view your Angular App with any browser on localhost:4200 like this :
Create New API Service
Now, we need to create new service for our API to remote HTTP servers via HttpClient module of Angular by sending HTTP requests. To create new service you can type this command :
ng generate service services/api
This command will give you new folder of your service in src/app directory like this :
Import HttpClientModule to app.module.ts :
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { HttpClientModule } from '@angular/common/http';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
@NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule,
HttpClientModule,
AppRoutingModule,
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
Open api.service.ts file and import HttpClient and HttpHeaders module in this service class.
import { Injectable } from '@angular/core';
import { HttpClient,HttpHeaders } from '@angular/common/http';
@Injectable({
providedIn: 'root'
})
export class ApiService {
constructor(
private http:HttpClient,
) { }
}
The HTTP methods commonly used in REST API are:
1. GET Method
This method usually used to read resources from the REST server. To use GET method, create new function call get on ApiService class :
import { Injectable } from '@angular/core';
import { HttpClient,HttpHeaders } from '@angular/common/http';
@Injectable({
providedIn: 'root'
})
export class ApiService {
constructor(
private http:HttpClient,
) { }
public get(url:any): Promise<any> {
return new Promise<any>((resolve, reject) => {
const header = {
headers: new HttpHeaders()
.set('Content-Type', 'application/x-www-form-urlencoded')
};
this.http.get(url, header).subscribe((data) => {
resolve(data);
}, error => {
resolve(error);
});
});
}
}
Now, open app.component.ts and import ApiService class :
import { Component, OnInit } from '@angular/core';
import { ApiService } from 'src/app/services/api.service';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
constructor(
public api: ApiService,
) { }
ngOnInit(): void {
}
}
Create get function on app.component.ts and use get function from ApiService class :
import { Component, OnInit } from '@angular/core';
import { ApiService } from 'src/app/services/api.service';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
datas : any;
constructor(
public api: ApiService,
) { }
ngOnInit(): void {
this.get();
}
get() {
this.api.get('https://dzkrrbb.com/tutorial/php-restapi/get_city.php').then((data: any) => {
if (data) {
console.log(data);
} else {
console.log('Not Found');
}
});
}
}
We use API server from this tutorial : https://dzkrrbb.medium.com/rest-api-with-php-get-post-put-delete-8365fe092618. You can change URL of API server with yours and you can see response of data from console like this :
This response contain list of city with id and name value. To show this data in your web app you need to store this data and bind it.
import { Component, OnInit } from '@angular/core';
import { ApiService } from 'src/app/services/api.service';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
datas : any;
constructor(
public api: ApiService,
) { }
ngOnInit(): void {
this.get();
}
get() {
this.api.get('https://dzkrrbb.com/tutorial/php-restapi/get_city.php').then((data: any) => {
if (data) {
this.datas = data.city;
console.log(data);
} else {
console.log('Not Found');
}
});
}
}
Open app.component.html file and modify like this :
<p>Response data :</p>
<ul>
<li *ngFor="let item of datas">{{item.name}}</li>
</ul>
<router-outlet></router-outlet>
Now, you can see your data bind on your HTML
2. POST Method
This method usually used to create new resources on the REST server. To use POST method, create new function call post on ApiService class :
import { Injectable } from '@angular/core';
import { HttpClient,HttpHeaders } from '@angular/common/http';
@Injectable({
providedIn: 'root'
})
export class ApiService {
constructor(
private http:HttpClient,
) { }
public get(url:any): Promise<any> {
return new Promise<any>((resolve, reject) => {
const header = {
headers: new HttpHeaders()
.set('Content-Type', 'application/x-www-form-urlencoded')
};
this.http.get(url, header).subscribe((data) => {
resolve(data);
}, error => {
reject(error);
});
});
}
public post(url:any, param:any): Promise<any> {
return new Promise<any>((resolve, reject) => {
const header = {
headers: new HttpHeaders()
.set('Content-Type', 'application/x-www-form-urlencoded')
};
this.http.post(url, param, header).subscribe((data) => {
resolve(data);
}, error => {
resolve(error);
});
});
}
}
To store new data to API server create new post function on app.component.ts
import { Component, OnInit } from '@angular/core';
import { ApiService } from 'src/app/services/api.service';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
datas : any;
id : any;
name : any;
constructor(
public api: ApiService,
) { }
ngOnInit(): void {
this.get();
}
get() {
this.api.get('https://dzkrrbb.com/tutorial/php-restapi/get_city.php').then((data: any) => {
if (data) {
this.datas = data.city;
console.log(data);
} else {
console.log('Not Found');
}
});
}
post() {
if (this.id === '' || this.name === '') {
alert('All Fields are required');
}
const param = 'id='+this.id+'&name='+this.name;
this.api.post('https://dzkrrbb.com/tutorial/php-restapi/post_city.php', param).then((data: any) => {
if (data) {
this.datas = data.city;
console.log(data);
} else {
console.log('Not Found');
}
});
}
}
We use API server from this tutorial : https://dzkrrbb.medium.com/rest-api-with-php-get-post-put-delete-8365fe092618. You can change URL and param of API server with yours and for store new data you can create form, but to do this you must import FormsModule to app.module.ts :
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { HttpClientModule } from '@angular/common/http';
import { FormsModule } from '@angular/forms';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
@NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule,
HttpClientModule,
AppRoutingModule,
FormsModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
And then open app.component.html file and create form with post function like this :
<p>Response data :</p>
<ul>
<li *ngFor="let item of datas">{{item.name}}</li>
</ul>
<hr/>
<p>Post New data :</p>
<table>
<tr>
<td>ID</td>
<td>
<input class="form-control" type="text" [(ngModel)]="id" [ngModelOptions]="{standalone: true}" placeholder="Data ID">
</td>
</tr>
<tr>
<td>Name</td>
<td>
<input class="form-control" type="text" [(ngModel)]="name" [ngModelOptions]="{standalone: true}" placeholder="Data ID">
</td>
</tr>
<tr>
<td colspan="2">
<button type="button" (click)="post()">Submit</button>
</td>
</tr>
</table>
<router-outlet></router-outlet>
Your form should be like this :
And if you sent new data for example ID = 4 and Name = New York, your API server will receive this data and send back again to your app.
Conclusion
Congratulation, now you can work with REST API in Angular. You can clone this tutorial from https://github.com/dzkrrbb/AngularAPI
If you have any suggestions for the next article please leave a comment :)