Câu hỏi phỏng vấn Angular
Câu hỏi

Làm thế nào để xử lý lỗi cho Http Client?

Câu trả lời

Để xử lý lỗi cho HttpClient trong Angular, bạn có thể sử dụng một số cách sau:

  1. Sử dụng toán tử catchError từ thư viện RxJS để bắt và xử lý lỗi khi thực hiện các yêu cầu HTTP. Bạn có thể kiểm tra thông tin lỗi thông qua đối tượng HttpErrorResponse và xử lý tùy theo mã trạng thái HTTP hoặc loại lỗi cụ thể[1][2][3].

    Ví dụ:

    typescript Copy
    import { HttpClient, HttpErrorResponse } from '@angular/common/http';
    import { catchError } from 'rxjs/operators';
    import { throwError } from 'rxjs';
    
    constructor(private http: HttpClient) {}
    
    getData() {
      return this.http.get('/api/data').pipe(
        catchError((error: HttpErrorResponse) => {
          if (error.status === 404) {
            // Xử lý lỗi 404 tại đây
          } else {
            // Xử lý các lỗi khác tại đây
          }
          return throwError(error);
        })
      );
    }
  2. Sử dụng HttpInterceptor để tạo một lớp trung gian xử lý lỗi cho tất cả các yêu cầu HTTP đi ra và phản hồi đến từ server. HttpInterceptor cho phép bạn can thiệp vào quá trình yêu cầu và phản hồi, từ đó có thể thực hiện xử lý lỗi một cách tập trung[2][3][4].

    Ví dụ:

    typescript Copy
    import { Injectable } from '@angular/core';
    import { HttpInterceptor, HttpRequest, HttpHandler, HttpEvent, HttpErrorResponse } from '@angular/common/http';
    import { Observable, throwError } from 'rxjs';
    import { catchError } from 'rxjs/operators';
    
    @Injectable()
    export class ErrorInterceptor implements HttpInterceptor {
      intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
        return next.handle(request).pipe(
          catchError((error: HttpErrorResponse) => {
            if (error.status === 401) {
              // Xử lý lỗi xác thực tại đây
            }
            // Xử lý các lỗi khác
            return th...
middle

middle

Gợi ý câu hỏi phỏng vấn

middle

Làm thế nào để chèn thẻ** base href**?

senior

Tôi có thể sử dụng jQuery với Angular không?

expert

Tại sao Incremental DOM có thể được Tree Shaking?

Bình luận

Chưa có bình luận nào

Chưa có bình luận nào