我正在尝试使用继承为我的服务制作一个通用错误处理程序,但出于某种原因,当它到达错误处理程序本身时,“this”似乎总是为空,我无法弄清楚为什么。我可以很好地进入错误处理程序,但我总是得到:
EXCEPTION: Uncaught (in promise): TypeError: Cannot read property 'http' of null
知道我遗漏了什么/做错了什么吗?不确定“this”怎么可能为空?
这是我的服务的整个基类:
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);
}
}
最佳答案
对于应该用作回调的方法,建议在构造时将它们绑定(bind)到上下文。在 TypeScript 中,这可以通过类字段和箭头方法实现:
constructor(public http: Http) {}
handleError = (error: any): Promise<any> { ... }
与绑定(bind)方法调用相反,这消除了不正确上下文的可能性。
更可取的方式可能是:
constructor(public http: Http) {
this.handleError = this.handleError.bind(this);
}
handleError(error: any): Promise<any> { ... }
它做同样的事情但具有更好的可测试性,因为它允许在类实例化之前监视/模拟 HttpServiceBase.prototype.handleError
。
关于javascript - angular2 服务基类继承 - 为什么 'this' 为空?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41386085/