I'm trying to create a universal error handler for my services using inheritance, but I'm facing an issue where 'this' is always null in the error handler. I can access the error handler, but I keep getting the following error:
EXCEPTION: Uncaught (in promise): TypeError: Cannot read property 'http' of null
Any suggestions on what might be missing or wrong in my approach? It's puzzling how 'this' can be null.
This is the base class for my service:
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);
}
}
And here is the inheriting class:
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);
}
}