简体   繁体   English

如何以角度获取http响应的状态代码?

[英]How to get status code of http response in angular?

I want to show a toast that will have text depending upon the status code of the HTTP response.我想根据 HTTP 响应的状态代码显示一个带有文本的吐司。 code from service:-服务代码:-

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)
  }

and this is what I am doing in frontend:-这就是我在前端所做的:-

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;
    });

  }

You can just call error.status from HttpErrorResponse.你可以叫error.status从HttpErrorResponse。

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

It`s better to use Error handling with interceptor最好将错误处理与拦截器一起使用

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",
    });
  }
}

add this tag in app.module.tsapp.module.ts 中添加这个标签

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM