angular使用攔截器統一配置介面錯誤提示
阿新 • • 發佈:2018-11-04
攔截器程式碼如下:
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<any>, next: HttpHandler): Observable<HttpEvent<any>> { 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<any>) => { // 請求失敗處理 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中進行註冊的話,只會在專案首次載入時有效)。