以angular

时间:2019-05-27 11:05:57

标签: angular http-error

我正在处理 http错误处理。我在每个组件中都编写了错误处理,这不是一个好的编码实践。因此,我决定在全局范围内编写一个常见的http错误处理。我已经搜索过它,遇到过http-interceptor概念,我认为有更好的方法来处理 HTTP 错误。我在每个组件中尝试过的内容都在下面,而不是我需要一个全局方法。我已经有http-interceptor文件,并且代码粘贴在下面。

component.ts:

this.serviceName.methodName().catch(err => {
  console.log("Something went wrong with the request, please try again.");
  return Observable.throw(err.message.toUpperCase() || 'API_ERROR');
}).subscribe((res) => {
   console.log(res);
},
 error=>{
    this.openSnackBar('danger', "Something went wrong with the request, please try again.");
 });

http-interceptor:

import { Injectable } from "@angular/core";
import { HttpInterceptor, HttpRequest, HttpHandler, HttpEvent, HttpResponse } from "@angular/common/http";
import { Observable } from "rxjs";
import { tap } from 'rxjs/operators';

@Injectable()
export class HttpErrorInterceptor implements HttpInterceptor {
constructor() { }

intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    return next.handle(request).pipe(tap(
        event => event instanceof HttpResponse ? 'succeeded' : '',
        err => 'failed'
    ))
 }
}

请帮助。谢谢。

1 个答案:

答案 0 :(得分:1)

尝试一下:

intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    return next.handle(request).pipe(tap(
      event => event instanceof HttpResponse ? 'succeeded' : '',
      err => {
        this.openSnackBar('danger', "Something went wrong with the request, please try again.");
      }
    ))
  }