Làm thế nào để thiết lập* header...
Làm thế nào để thiết lập* header...
Để thiết lập headers cho mọi yêu cầu trong Angular, bạn có thể sử dụng HttpHeaders trong HttpClientModule. HttpHeaders là immutable, nghĩa là mỗi lần bạn muốn thay đổi giá trị của nó, bạn cần tạo một instance mới với giá trị đã được chỉnh sửa. Dưới đây là một ví dụ về cách thiết lập headers cho một yêu cầu GET:
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Observable } from 'rxjs';
export class PostService {
constructor(private httpClient: HttpClient) {}
getListPosts(): Observable<PostEntityModel[]> {
let headers: HttpHeaders = new HttpHeaders();
headers = headers.set('angularVN', 'Angular Viet Nam');
return this.httpClient.get<PostEntityModel[]>(
'https://jsonplaceholder.typicode.com/posts',
{ headers }
);
}
}
Trong ví dụ trên, chúng ta tạo một instance của HttpHeaders và sử dụng phương thức set để thêm một header mới với tên là 'angularVN' và giá trị là 'Angular Viet Nam'. Sau đó, chúng ta truyền...
senior