HttpClient

What is the HttpClient?

  • Provides API for network communication

  • Supports making HTTP request using (GET, POST, PUT, DELETE, etc verbs)

  • Handles headers for requests and responses

  • Built on RxJs Observables for asynchronous operations

Import HttpClient

core.module.ts
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { HttpClientModule } from '@angular/common/http';
import { SharedModule } from '../shared/shared.module';
import { UserService } from './user.service';
@NgModule({
imports: [
CommonModule,
HttpClientModule,
SharedModule
],
declarations: [],
providers: [UserService]
})
export class CoreModule {}

HttpClient Example

user.service.ts
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';
@Injectable({providedIn: 'root'})
export class UserService {
constructor(private http: HttpClient) { }
test() {
let data: Observable<Object> = this.http.get('users/1');
data.subscribe(result => console.log(result));
}
}

HttpClient Service

Demo API

Observables

  • Angular uses the RxJS library to handle async operations

  • Observables provide a way to consume async data/events streams

    • Observables can be subscribed to and get data when the source emits a new value

  • Observables can be used to transform data

Implementing a Service in a Component

users.component.ts
import { Component, OnInit } from '@angular/core';
import { Observable } from 'rxjs';
import { UserService } from '../core/user.service';
import { User } from '../core/user.model';
import { HttpErrorResponse } from '@angular/common/http';
@Component({
selector: 'app-users',
templateUrl: './users.component.html',
styleUrls: ['./users.component.css']
})
export class UsersComponent implements OnInit {
users: User[];
constructor(private userService: UserService) {}
ngOnInit() {
this.userService
.getUsers()
.subscribe(
(users: User[]) => this.users = users,
(error: HttpErrorResponse) => console.log(error)
);
}
}

Complete Service

user.service.ts
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';
import { User } from './user.model';
@Injectable({
providedIn: 'root'
})
export class UserService {
constructor(private http: HttpClient) {}
getUser(id: number): Observable<User> {
return this.http.get<User>(`/users/${id}`);
}
getUsers(): Observable<User[]> {
return this.http.get<User[]>('/users');
}
createUser(user: User): Observable<User> {
return this.http.post<User>('/users', user);
}
updateUser(user: User): Observable<User> {
return this.http.put<User>(`/users/${user.id}`, user);
}
deleteUser(user: User): Observable<User> {
return this.http.delete<User>(`/users/${user.id}`);
}
}

Summary

  • What is the HttpClient

  • Importing HttpClientModule

  • Making http calls

  • Observables introduction