-1
我正在嘗試爲我的Angular4應用程序編寫一個簡單的http攔截器,以處理基本的事情,例如將加載微調器關閉,稍微記錄日誌或者在某些時候緩存。在Angular2攔截器中處理錯誤
這是我到目前爲止有:
import { Injectable } from '@angular/core';
import { HttpEvent, HttpInterceptor, HttpHandler, HttpRequest } from
'@angular/common/http';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/do';
import { HttpResponse } from '@angular/common/http';
import { LoadingOverlayService } from '../../../services/loadingoverlay/loadingoverlay.service';
import { MdSnackBar } from '@angular/material';
@Injectable()
export class MainInterceptor implements HttpInterceptor {
request: HttpRequest<any>;
constructor(public loadingOverlay: LoadingOverlayService, public snackBar: MdSnackBar) {
}
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
this.request = req;
let options = this._dealwithOptions();
if (!options.disableOverlay)
this.loadingOverlay.sync(true);
const started = Date.now();
return next.handle(this.request)
.do(event => {
console.log(event);
if (event instanceof HttpResponse) {
console.log(HttpResponse);
const elapsed = Date.now() - started;
console.log(`Request for ${req.urlWithParams} took ${elapsed} ms.`);
if (!options.disableOverlay)
this.loadingOverlay.sync(false);
}
});
}
_dealwithOptions() {
let rtrn: any = {};
var options = this.request.headers.get('requestoptions');
if (options != null) {
rtrn = JSON.parse(options);
this.request = this.request.clone({ headers: this.request.headers.delete('requestoptions') });
}
return (rtrn);
}
}
LoadingOverlayService
是我自己的服務,通過覆蓋或關閉的消息到具有覆蓋HTML組件。
一切工作正常直到有一個錯誤來自服務器。如何在攔截器中捕獲,讀取和傳遞錯誤事件?的.do()