Doing our first big App we have encounter a problem that supposed to be fixed in typescript 2.0+
Having the Abstract class:
export abstract class HttpBaseService {
protected abstract readonly TAG: any;
protected abstract _state: GlobalState;
private r = Math.random();
protected extractData(res: Response) {
console.log(`${this.TAG}:extractData:`, res.json());
const data = res.json() || [];
return data;
}
protected handleErrors(error: Response) {
console.error(`${this.TAG}:handleErrors:`, error);
console.log(this.TAG);
console.log(this._state);
if (error.status === 401 || error.status === 403) {// Not Authorized
console.error(`${this.TAG}:handleErrors: NOT AUTHORIZED`, error);
this._state.notifyDataChanged("logout", error);
}
return Observable.throw(error.json());
}
}
and the implementation:
@Injectable()
export class AlbumService extends HttpBaseService {
TAG = AlbumService.name;
constructor(protected _state: GlobalState,
private http: Http,
private auth: AuthService,
private localStorage: LocalStorageService,) {
super();
this._state = _state;
}
albums() {
console.log(`${this.TAG}:albums:`);
console.log(this._state);
const ALBUMS_URL = this.albumsUrl();
const token = this.auth.getToken();
const headers = new Headers();
headers.append('Authorization', `Token ${token}`);
return this.http
.get(`${Constants.API_URL}${ALBUMS_URL}`, {headers})
.catch(this.handleErrors)
.map(this.extractData);
}
}
When the function handleError from the super class is executed in a sub class has both parameters TAG and _state as "undefined"
Notice that i have test it putting it abstract, protected, public, from the constructor, manually assigning the members, and maybe several others.
I have to be missing something, because in the sub class constructor, i tried calling the handleError method after the assigning of _state and it works as expected, having a value for TAG an a value for _state.
UPDATE: Reducing the problem to a minimun
Now i have:
export abstract class HttpBaseService {
protected abstract _state: GlobalState;
protected handleErrors(error: Response) {
console.log(this._state);
}
protected extractData(res: Response) {
const data = res.json() || [];
return data;
}
}
and the implementation:
@Injectable()
export class AlbumService extends HttpBaseService {
constructor(_state: GlobalState,
private http: Http,
private auth: AuthService,
private localStorage: LocalStorageService,) {
super();
this._state = _state;
}
albums() {
const token = this.auth.getToken();
const headers = new Headers();
headers.append('Authorization', `Token ${token}`);
return this.http
.get(`${Constants.API_URL}`, {headers})
.catch(this.handleErrors)
.map(this.extractData);
}
}