如何用angular2拦截http错误?

Phi*_*lip 7 http http-response-codes angularjs angular

是否有类似于1.x的InterceptorAPI 的API?

我希望能够在应用程序启动时添加拦截器

  • 每当401返回状态代码时显示登录对话框
  • 每当5xx返回状态代码时显示一般错误消息

对于应用程序所做的每个http请求.

Jig*_*gar 3

您可以创建自己的 HTTPConnection 来处理错误,并在引导时将其注入到根应用程序组件中。

export class CustomHTTPConnection implements Connection
{
}
Run Code Online (Sandbox Code Playgroud)

然后在引导时注入它,如下所示

bootstrap([provider(Connection,{useClass:CustomHTTPConnection}]);
Run Code Online (Sandbox Code Playgroud)

如果您不想提供自定义连接类,您可以为每个单独的请求执行此操作,因为 Http 返回一个可观察的值,其中包含 3 个参数:onNext、onError、onCompleted。

您可以按如下方式使用它:

class Component
{
constructor(private httpService:HttpService){
}
onInit(){
 this.httpService.getData().subscribe(
  ()=>{},  //on Next
  ()=>{}   //onError
}
}
Run Code Online (Sandbox Code Playgroud)