Angular2拦截器中的错误处理

时间:2017-09-22 21:09:27

标签: angular

我正在尝试为我的Angular4应用程序编写一个简单的http拦截器来处理基本的事情,例如关闭加载微调器,或许在某些时候进行缓存。

这是我到目前为止所做的:

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的组件。

一切正常,直到服务器发生错误。如何在拦截器中捕获,读取和传递错误事件?

1 个答案:

答案 0 :(得分:0)

.do()的第二个输入参数为errorHandler,请参阅https://github.com/Reactive-Extensions/RxJS/blob/master/doc/api/core/operators/do.md