angular使用拦截器统一配置接口错误提示

拦截器代码如下:

import {Injectable} from '@angular/core';
import {HttpEvent, HttpInterceptor, HttpHandler, HttpRequest, HttpResponse} from '@angular/common/http';
import {Observable} from 'rxjs/Observable';
import {ErrorObservable} from 'rxjs/observable/ErrorObservable';
import {catchError} from 'rxjs/operators';
import {mergeMap} from 'rxjs/operators';
@Injectable()
export class InterceptorService implements HttpInterceptor {
  constructor(private messageService: MessageService, private translate: TranslateService) {}

  intercept(req: HttpRequest, next: HttpHandler): Observable> {
    return next.handle(req).pipe(mergeMap((event: any) => {
        const err = event.body && event.body.err;
        if (err) {
          switch (err) {
            case -1:
              // 在提示框中展示错误消息
              break;
            default:
              break;
          }
        }
        if (event instanceof HttpResponse && event.status !== 200) {
          return ErrorObservable.create(event);
        }
        return Observable.create(observer => observer.next(event)); // 请求成功返回响应
      }),
      catchError((res: HttpResponse) => {   // 请求失败处理
        this.messageService.clear();
        switch (res.status) {
          case 500:
            // 提示请求超时
            break;
          default:
            // 提示网络错误
        }
        return ErrorObservable.create(event);
      }));
  }
}

在对应module中注册提供商:

import {HTTP_INTERCEPTORS, HttpClientModule} from '@angular/common/http';

@NgModule({
    providers: [
    {provide: HTTP_INTERCEPTORS, useClass: InterceptorService, multi: true}
    ]
})
export class SharedModule {
}

如果所有模块都需要用拦截器的话,可以在shareModule中进行注册(如果在app.module中进行注册的话,只会在项目首次加载时有效)。

你可能感兴趣的:(ng)