- vừa được xem lúc

Sử dụng HttpClient trong Angular thực hiện các yêu cầu HTTP đến các API server

0 0 17

Người đăng: Vũ Mạnh Tuấn

Theo Viblo Asia

HttpClient là một class trong Angular cung cấp cho chúng ta các method để thực hiện các yêu cầu HTTP đến các API server. Đây là một trong những class quan trọng nhất trong Angular để tương tác với backend. Dưới đây là một số cách sử dụng HttpClient trong Angular:

1. Import HttpClient module

Trước khi sử dụng HttpClient, chúng ta cần import module HttpClientModule vào trong AppModule.

import { HttpClientModule } from '@angular/common/http'; @NgModule({ imports: [ HttpClientModule ]
})

2. Thực hiện GET request

import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs'; @Injectable()
export class MyService { constructor(private http: HttpClient) {} getData(): Observable<any> { return this.http.get('https://jsonplaceholder.typicode.com/posts'); }
}

Ở đây, chúng ta import HttpClient vào trong service và sử dụng method get để thực hiện GET request. get trả về một Observable, nó sẽ phát ra kết quả khi có response từ server.

3. Thực hiện POST request

import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Observable } from 'rxjs'; @Injectable()
export class MyService { constructor(private http: HttpClient) {} postData(data): Observable<any> { const headers = new HttpHeaders() .set('Content-Type', 'application/json'); return this.http.post('https://jsonplaceholder.typicode.com/posts', data, { headers }); }
}

Ở đây, chúng ta sử dụng method post để thực hiện POST request. post nhận ba tham số: URL, dữ liệu cần gửi và options (nếu có). Trong ví dụ trên, chúng ta cũng tạo ra một header để định dạng dữ liệu là JSON.

4. Xử lý lỗi

import { HttpClient, HttpErrorResponse } from '@angular/common/http';
import { catchError } from 'rxjs/operators';
import { throwError } from 'rxjs'; @Injectable()
export class MyService { constructor(private http: HttpClient) {} getData(): Observable<any> { return this.http.get('https://jsonplaceholder.typicode.com/posts') .pipe( catchError(this.handleError) ); } private handleError(error: HttpErrorResponse) { let errorMessage = 'Something went wrong'; if (error.error instanceof ErrorEvent) { // client-side error errorMessage = `Error: ${error.error.message}`; } else { // server-side error errorMessage = `Error Code: ${error.status}\nMessage: ${error.message}`; } console.log(errorMessage); return throwError(errorMessage); }
}

Trong ví dụ trên, chúng ta sử dụng catchError để xử lý lỗi. Nếu có lỗi, handleError sẽ được gọi và trả về một Observable với kết quả là lỗi. Chúng ta có thể định nghĩa cách xử lý lỗi trong handleError và trả về kết quả mà chúng ta mong muốn

5. Thực hiện PUT request

import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Observable } from 'rxjs'; @Injectable()
export class MyService { constructor(private http: HttpClient) {} putData(data): Observable<any> { const headers = new HttpHeaders() .set('Content-Type', 'application/json'); return this.http.put('https://jsonplaceholder.typicode.com/posts/1', data, { headers }); }
}

Ở đây, chúng ta sử dụng method put để thực hiện PUT request. put nhận ba tham số: URL, dữ liệu cần gửi và options (nếu có). Trong ví dụ trên, chúng ta cũng tạo ra một header để định dạng dữ liệu là JSON.

6. Thực hiện DELETE request

import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs'; @Injectable()
export class MyService { constructor(private http: HttpClient) {} deleteData(): Observable<any> { return this.http.delete('https://jsonplaceholder.typicode.com/posts/1'); }
}

Ở đây, chúng ta sử dụng method delete để thực hiện DELETE request.

7. Sử dụng query parameters

import { HttpClient, HttpParams } from '@angular/common/http';
import { Observable } from 'rxjs'; @Injectable()
export class MyService { constructor(private http: HttpClient) {} getDataById(id: number): Observable<any> { const params = new HttpParams() .set('id', id.toString()); return this.http.get('https://jsonplaceholder.typicode.com/posts', { params }); }
}

Ở đây, chúng ta sử dụng HttpParams để tạo query parameters và truyền chúng vào GET request.

Trên đây là một số cách sử dụng HttpClient trong Angular. Các method khác của HttpClient cũng tương tự như các ví dụ trên. Bạn có thể tham khảo thêm trong Angular Documentation.

https://angular.io/guide/http

Bình luận

Bài viết tương tự

- vừa được xem lúc

Route in Angular JS

Router là một module được đặt tại @angular/router, cung cấp cho ứng dụng Angluar của chúng ta khả năng điều hướng và hiển thị nội dung phù hợp với địa chỉ URL. Với các ứng dụng web thông thường, việc điều hướng theo URL thường sẽ do phía server đảm nhiệm, giống như hình ảnh dưới đây là ví dụ với Rai

0 0 84

- vừa được xem lúc

Có gì mới trong Angular 11

Phiên bản Angular 11.0.0 được phát hành vào tháng 11 năm 2020. Bản phát hành chính Angular 11 cung cấp các bản cập nhật trên toàn bộ nền tảng, bao gồm CLI và các components.

0 0 89

- vừa được xem lúc

Pipe trong Angular

Xin chào tất cả mọi người, bài viết này minh xin giới thiệu về Pipe trong Angular, rất mong được mọi người theo dõi. 1) Pipe trong Angular là gì. . .

0 0 113

- vừa được xem lúc

Angular Reactive Forms: Cách sử dụng FormArray

Trong bài viết này chúng ta sẽ tìm hiểu khi nào và cách sử dụng FormArray, cả trong Component và trong Template, ngoài ra chúng ta sẽ xem cách để custom validation cho nó. Vì sao chúng ta cần sử dụng FormArray.

0 0 92

- vừa được xem lúc

RxJS và Reactive Programming

1 - Stream. Streams are a sequence of values over time.

0 0 341

- vừa được xem lúc

Mapping class Java với Angular Typescript model – Chưa bao giờ dễ đến thế

Xin chào mọi người hôm nay mình giới thiệu một loại đồ chơi cực xịn cực hay ho luôn, đây là một thư viện giúp cho mọi người tạo ra 1 class Typescript trong dự án Frontend ở đây mình lấy ví dụ là Angul

0 0 81