如何获取Angular HTTP响应的状态码?

问题描述

我想展示一个烤面包,该烤面包的文本取决于HTTP响应的状态码。 服务中的代码:-

private options = {
    headers: new HttpHeaders()
      .set("Content-Type","application/json")
      .set("x-app-id",this.appId)
      .set("x-app-key",this.appKey)
      .set("observe","response")
  };
  constructor(private http: HttpClient) {}
  search(query: string): Observable<{}>  {
    return this.http.post(this.url,{query: query},this.options)
  }

这就是我在前端所做的:-

search() {
    this.showcard = false;
    this.isLoading = true;
    this.nutrix.search(this.searchValue).subscribe((res) => {
      if(res){
        this.isLoading = false;
        this.showcard = true;
        this.queryResult = res["foods"][0];
        this.imageUrl = this.queryResult['photo']['thumb']
      }
      console.log(this.queryResult);
    },(error) => {
      console.log(error);
      this.isLoading = false;
    });

  }

解决方法

您可以只从HttpErrorResponse调用error.status

this.nutrix.search(this.searchValue).subscribe((res) => {
    // response
},(error) => {
    console.log(error.status);
});
,

最好与拦截器一起使用错误处理

import {
 HttpEvent,HttpInterceptor,HttpHandler,HttpRequest,HttpResponse,HttpErrorResponse
} from '@angular/common/http';
import { Observable,throwError } from 'rxjs';
import { retry,catchError } from 'rxjs/operators';
import { ToastrService } from "ngx-toastr";
import { Router } from "@angular/router";

export class HttpErrorInterceptor implements HttpInterceptor {
constructor(private toastr: ToastrService,private router: Router) {}
 intercept(request: HttpRequest<any>,next: HttpHandler): Observable<HttpEvent<any>> {
   return next.handle(request)
     .pipe(
       retry(1),catchError((error: HttpErrorResponse) => {
         if (error instanceof HttpErrorResponse) {
      if (error.error instanceof ErrorEvent) {
        console.log("Error Event");
      } else {
        console.log(
          `error status : ${error.status} ${JSON.stringify(error.error)}`
        );
        switch (error.status) {
          case 401:
            this.router.navigateByUrl("/login");
            break;
          case 403:
            this.router.navigateByUrl("/unauthorized");
            break;
          case 0:
          case 400:
          case 405:
          case 406:
          case 409:
          case 500:
            this.handleAuthError(error);
            break;
        }
      }
    } else {
      console.error("something else happened");
    }

    return throwError(error);
       })
     )
 }
public handleAuthError(error: any) {
    console.log("error ",error);
    let msg = "";
    if (error !== undefined && typeof error === "string") {
      msg = error;
    } else if (error.error !== undefined && typeof error.error === "string") {
      msg = error.error;
    } else if (
      error.error.error !== undefined &&
      typeof error.error.error === "string"
    ) {
      msg = error.error.error;
    } else {
      msg = error.error.error.errors
        ? error.error.error.errors[0].errorMessage
        : "Something went wrong";
    }
    this.toastr.error(msg,"",{
      timeOut: 3000,positionClass: "toast-bottom-center",});
  }
}

将此标签添加到 app.module.ts

providers: [
   {
     provide: HTTP_INTERCEPTORS,useClass: HttpErrorInterceptor,multi: true
   }
 ]

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...