Angular 使用服务的角度HTTP拦截器
我试图利用Angular 4.3+中新的HTTP拦截器功能。我的拦截器工作正常。但是我想捕获错误并使用Angular 使用服务的角度HTTP拦截器,angular,Angular,我试图利用Angular 4.3+中新的HTTP拦截器功能。我的拦截器工作正常。但是我想捕获错误并使用angular2 toaster发出toast样式的通知。我将所有toast功能放在一个服务中,ToasterNotificationService。但是,当我试图在拦截器中使用该服务时,情况就不那么好了 如果我只是通过在构造函数中初始化来尝试在拦截器中使用ToasterNotificationService,我会得到一个错误,即没有xxx的提供程序。因此,如果我从@angular/core导入
angular2 toaster
发出toast样式的通知。我将所有toast功能放在一个服务中,ToasterNotificationService
。但是,当我试图在拦截器中使用该服务时,情况就不那么好了
如果我只是通过在构造函数中初始化来尝试在拦截器中使用ToasterNotificationService
,我会得到一个错误,即没有xxx的提供程序。因此,如果我从@angular/core
导入注入器
,在构造函数中初始化该注入器,然后尝试手动将的一个实例注入到sternotificationservice
,请求就会终止。就像,它实际上停止,并且永远不会发送到服务器。下面是我的拦截器中我的拦截
函数的一个示例:
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);
});
}
我已经尝试在HTTP\u拦截器前后将声明为sternotificationservice
,我发现了错误。我从angular2 toaster
导入ToasterService
,并在我的自定义ToasterNotificationService
中使用它,但从未在我的应用程序的提供商中声明过这一点。一旦这样做了,声明了所有三个服务,一切又恢复了正常。您是否在导入拦截器的同一模块中导入了toast服务?只是想问一个同样的问题,如果您正确配置了Toaster服务的提供程序,您在不使用injectorSorry的情况下应该会遇到注入问题,我本应该把这一部分放在原来的问题中。查看编辑以了解我如何声明app.module.ts
的提供程序。是否导入toastermodule?如果没有,能否从提供程序中删除服务,导入模块,然后在拦截器中使用构造函数方法重试?奇怪的是@pjlamb12I没有导入烤面包机模块
,但即使尝试一下也会得到同样的结果。该请求已终止,甚至从未发送到服务器。对于此问题上的其他障碍,请尝试将此装饰程序添加到拦截器@Injectable({providedIn:'root'})导出类HttpErrorInterceptor实现HttpInterceptor{
,它对我有效。
providers: [
ToasterNotificationService,
{
provide: HTTP_INTERCEPTORS,
useClass: ErrorInterceptorService,
multi: true,
}
]