我正在尝试使用继承来为我的服务做一个通用错误处理程序,但是由于某种原因,当它到达错误处理程序本身时,'this'似乎总是为null,我不知道原因。我可以进入错误处理程序,但是我总是得到:
例外:未被告求(在承诺中):TypeError:无法阅读属性 null的'http'
知道我想念/做错了什么吗?不确定"这个"怎么可能为null?
这是我服务的整个基类:
import { Injectable } from '@angular/core';
import { Http } from '@angular/http';
@Injectable()
export class HttpServiceBase {
constructor(public http: Http) {
console.log('http', this.http); //just do this to prove that it is there - it is!
}
handleError(error: any): Promise<any> {
console.error('Application Error', error); //this logs fine
// TypeError: Cannot read property 'http' of null
this.http.get('/Account/IsLoggedIn')
.map(response => console.log('RESPONSE: ', response));
return Promise.reject(error.message || error);
}
}
这是我的继承类:
import 'rxjs/add/operator/toPromise';
import { Injectable } from '@angular/core';
import { Headers, Http } from '@angular/http';
import { HttpServiceBase } from './http-service.base';
import { Hero } from './hero';
@Injectable()
export class HeroService extends HttpServiceBase {
private headers = new Headers({ 'Content-Type': 'application/json' });
private heroesUrl = 'http://localhost:57569/Home/Heroes';
constructor(http: Http) { super(http); }
getHeroes(): Promise<Hero[]> {
console.log('getting heroes');
return this.http.get(this.heroesUrl + '-force-error') //so it will error out
.toPromise()
.then(response => response.json() as Hero[] )
.catch(this.handleError);
}
}
对于应该用作回调的方法,建议将它们绑定到构造上的上下文中。在打字稿中,这是可以通过类字段和箭头方法来实现的:
constructor(public http: Http) {}
handleError = (error: any): Promise<any> { ... }
而不是对方法呼叫的约束,这消除了不正确上下文的可能性。
更可取的方法可能是:
constructor(public http: Http) {
this.handleError = this.handleError.bind(this);
}
handleError(error: any): Promise<any> { ... }
它做同样的事情,但具有更好的可测试性,因为它允许在类实例化之前监视/模拟HttpServiceBase.prototype.handleError
。
发生了,因为您将 handleRor 作为catch函数的函数传递给 handleRor 。当它被称为时,它将具有不同的此对象。
您可以将箭头函数传递到 catch 保留相同的上下文。
.catch(error => this.handleError(error));
您必须记住,即使 handleRor 被定义为类的方法,它仍然像任何其他功能一样行为。
是否有任何机会修复它?
.catch(this.handleError.bind(this));