【发布时间】:2015-12-30 00:26:23
【问题描述】:
是否有类似于 angular 1.x 的Interceptor API 的 API?
我希望能够在应用程序启动时添加拦截器
- 每当返回
401状态码时显示登录对话框 - 每当返回
5xx状态代码时显示一般错误消息
对于应用程序发出的每个 http 请求。
【问题讨论】:
标签: angularjs http angular http-response-codes
是否有类似于 angular 1.x 的Interceptor API 的 API?
我希望能够在应用程序启动时添加拦截器
401 状态码时显示登录对话框5xx 状态代码时显示一般错误消息对于应用程序发出的每个 http 请求。
【问题讨论】:
标签: angularjs http angular http-response-codes
您可以创建自己的 HTTPConnection 来处理错误并在引导时将其注入到根应用程序组件中。
export class CustomHTTPConnection implements Connection
{
}
然后在引导时注入它,如下所示
bootstrap([provider(Connection,{useClass:CustomHTTPConnection}]);
如果您不想提供自定义连接类,您可以为每个单独的请求执行此操作,因为 Http 返回一个 observable,它作为 3 个参数:onNext、onError、onCompleted。
您可以按如下方式使用它:
class Component
{
constructor(private httpService:HttpService){
}
onInit(){
this.httpService.getData().subscribe(
()=>{}, //on Next
()=>{} //onError
}
}
【讨论】: