HttpClient
is used to make HTTP requests, like GET | POST | PUT | DELETE to back end server.
The Angular HTTP client module is firstly introduced in the Angular
4.3 version.
This new API is available in the package @angular/common/http.
This is a replacement for the old HttpModule.
The HTTP Client makes use of the RxJs Observables
. The response from the HttpClient
is observable, so it needs to be subscribed.
Import HttpClient Module in Root Module
STEP 1
The first thing is to import the HttpClientModule in app.module.ts .
import {
HttpClientModule
} from '@angular/common/http';
imports: [
HttpClientModule
],
Import Required Module in Component/Service and then Inject HttpClient service
import {
HttpClient
} from '@angular/common/http';
constructor(public http: HttpClient) {}
STEP 2
Define your base URL of API and inject the HttpClient in the service constructor. Then, define your GET/POST/PUT/DELETE calls as shown below:
import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Observable, throwError } from 'rxjs';
import { catchError } from 'rxjs/operators';
import { User } from '../User';
@Injectable({
providedIn: 'root'
})
export class UserService {
private apiURL = "http://localhost:56299/api/"; //YOUR API URL
httpOptions = {
headers: new HttpHeaders({
'Content-Type': 'application/json'
})
}
constructor(private httpClient: HttpClient) {}
getUsers(): Observable < User[] > {
return this.httpClient.get < User[] > (this.apiURL + 'userapi/').pipe(catchError(this.errorHandler));
}
addUser(user: User): Observable < User > {
return this.httpClient.post < User > (this.apiURL + 'userapi/', JSON.stringify(user), this.httpOptions).pipe(catchError(this.errorHandler))
}
getUsersByID(id: number): Observable < User > {
return this.httpClient.get < User > (this.apiURL + '/userapi/' + id).pipe(catchError(this.errorHandler))
}
updateUser(user: User): Observable < User > {
return this.httpClient.put < User > (this.apiURL + '/userapi/' + user.id, JSON.stringify(user), this.httpOptions).pipe(catchError(this.errorHandler))
}
removeUser(id: number) {
return this.httpClient.delete < User > (this.apiURL + 'userapi/' + id, this.httpOptions).pipe(catchError(this.errorHandler));
}
errorHandler(error: {
error: {
message: string;
};status: any;message: any;
}) {
let errorMessage = '';
if (error.error instanceof ErrorEvent) {
errorMessage = error.error.message;
} else {
errorMessage = `Error Code: ${error.status}\nMessage: ${error.message}`;
}
return throwError(errorMessage);
}
}
STEP 3
In your component file, subscribe to the service to get the response:
//GET
this.userService.getUsers().subscribe((data: User[]) => {
this.userList = data;
});
//DELETE
this.userService.removeUser(id).subscribe(() => {
this.refreshUser();
});
//POST
this.userService.addUser(this.userform.value).subscribe((data: User) => {
//Redirecting to user List page after save or update
this.router.navigate(['/user']);
});
//PUT
this.userService.updateUser(this.userform.value).subscribe((data: User) => {
//Redirecting to user List page after save or update
this.router.navigate(['/user']);
});
Now run the code using the npm start command.
Please use the GitHub link to download the source code: