我正在嘗試使用繼承來爲我的服務創建一個通用錯誤處理程序,但由於某種原因,當它到達錯誤處理程序本身時,'this'總是顯示爲空,而我無法弄清楚原因。我可以進入錯誤處理得很好,但我總是得到:angular2服務基類繼承 - 爲什麼'this'爲null?
EXCEPTION: Uncaught (in promise): TypeError: Cannot read property 'http' of 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);
}
}
所有正確的答案,但這是最完整的!非常感謝你! – naspinski
當然,不客氣。 – estus