angular 2-HTTP错误处理程序中注入的服务 [英] angular 2 - Injected service in http error handler

查看:87
本文介绍了angular 2-HTTP错误处理程序中注入的服务的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个方法handleError(),如文档

I have a method handleError() like in the documentation https://angular.io/docs/ts/latest/guide/server-communication.html#!#error-handling

private handleError(error: any) {
    console.error(error);
    console.log(this.loginService); // <- always undefined
    return Observable.throw(error);
}

我的问题是,尽管 this.loginService 未定义,但已正确地将其插入了我的班级.它已在其他方法中使用,但在 handleError 中似乎不可用.

My problem is, that this.loginService is undefined although it has been injected in my class correctly. It is already used in other methods but seems not to be available in handleError.

http-catch调用方法的方式可能是问题吗? 如果是这样,我该如何解决?处理错误时,我需要执行一些逻辑.

Could the way the method is called by the http-catch be the problem? If so, how can i come around that? I need to execute some logic when handling an error.

这是一个有关如何将handleError方法设置为回调(与文档完全一样)的示例

This is an example on how i set handleError method as callback (exactly like documentation)

this.http.get(url,
              ApiRequest.ACCEPT_JSON)
              .map(ApiHelper.extractData)
              .catch(this.handleError);

推荐答案

由于直接传递函数,因此您的类中没有this上下文.一种真正简单且最佳实践的方法是使用lambda或胖箭头功能":

Since you're passing the function directly, you don't have the this context of your class in there. A really easy and best practice way would be to use a lambda or "fat arrow function":

this.http.get(url, ApiRequest.ACCEPT_JSON)
    .map(res => ApiHelper.extractData(res))
    .catch(err => this.handleError(err));


关于何时使用lambda的非常好的阅读: https://stackoverflow.com/a/23045200/1961059

这篇关于angular 2-HTTP错误处理程序中注入的服务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆