使用服务的角度HTTP拦截器

时间:2017-09-01 18:36:20

标签: angular

我试图利用Angular 4.3+中的新HTTP拦截功能。我的拦截器工作得很好。但我想捕获错误并使用angular2-toaster发出一个吐司式通知。我将所有Toast功能放在服务ToasterNotificationService中。但是当我尝试在拦截器中使用该服务时,事情就不会那么好了。

如果我只是通过在构造函数中初始化它来尝试在拦截器中使用ToasterNotificationService,则会收到No provider for xxx的错误。那么如果我从Injector导入@angular/core,在构造函数中初始化它,然后尝试手动注入ToasterNotificationService的实例,请求就会死亡。就像,它从字面上停止,永远不会发送到服务器。这是我的拦截器中intercept函数的一个例子:

intercept (req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    console.log(req);
    const toaster = this.injector.get(ToasterNotificationService);


    return next.handle(req)
        .do((ev: HttpEvent<any>) => {
            if (ev instanceof HttpResponse) {
                console.log('ev in the do: ', ev);
            }
        })
        .catch((response: any) => {
            if (response instanceof HttpErrorResponse) {
                console.log('response in the catch: ', response);
                toaster.error('Unexpected Error', response.error.message);
            }

            return Observable.throw(response);
        });
}

执行此操作时,第2行上的console.log有效,但请求将终止。控制台或终端中不会弹出任何错误,请求永远不会到达服务器。

如果我只注释掉引用烤面包机的两行,请求就会进入服务器。

有没有人对我可以做些什么来绕过这个问题?

修改

这是我app.module.ts的提供者部分,我宣布这两项服务:

providers: [
    ToasterNotificationService,
    {
        provide: HTTP_INTERCEPTORS,
        useClass: ErrorInterceptorService,
        multi: true,
    }
]

我已尝试在ToasterNotificationService之前和之后声明HTTP_INTERCEPTORS

1 个答案:

答案 0 :(得分:0)

我弄明白了这个错误。我从ToasterService导入angular2-toaster并在我的自定义ToasterNotificationService中使用它,但从未在我的应用的providers中声明。一旦这样做,宣布所有三项服务,一切都按预期工作。