Hey there! I'm currently working on an Angular 2 application and running into some trouble with observables for HTTP requests. Everything seems to work well in general, but I'm curious as to why it appears to be losing track of 'this'?
loginWithEmailAndPassword(email: string, password: string){
let headers = new Headers({ 'Content-Type': 'application/json'});
let options = new RequestOptions({ headers: headers});
return this.http.post('auth/login', {email: email, password: password}, options)
.map(this.extractData)
.catch(this.handleError)
}
private extractData(res: Response) {
let body = res.json();
// console.log(body);
if (body.token){
this.saveToken(body.token);
localStorage.setItem('token', body.token);
}
return body || {}
}
private saveToken(token: string){
localStorage.setItem('token', token);
}
Within the block
if (body.token){
this.saveToken(body.token);
localStorage.setItem('token', body.token);
}
I encounter the error
user.service.ts:54 TypeError: this.saveToken is not a function
at MapSubscriber.webpackJsonp.../../../../../src/app/user/user.service.ts.UserService.extractData [as project] (user.service.ts:31)
at MapSubscriber.webpackJsonp.../../../../rxjs/operator/map.js.MapSubscriber._next (map.js:77)
at MapSubscriber.webpackJsonp.../../../../rxjs/Subscriber.js.Subscriber.next (Subscriber.js:89)
at XMLHttpRequest.onLoad (http.es5.js:1226)
at ZoneDelegate.webpackJsonp.../../../../zone.js/dist/zone.js.ZoneDelegate.invokeTask (zone.js:424)
at Object.onInvokeTask (core.es5.js:3881)
at ZoneDelegate.webpackJsonp.../../../../zone.js/dist/zone.js.ZoneDelegate.invokeTask (zone.js:423)
at Zone.webpackJsonp.../../../../zone.js/dist/zone.js.Zone.runTask (zone.js:191)
at XMLHttpRequest.ZoneTask.invoke (zone.js:486)
Could someone advise me on the correct way to reference other methods within a class using this pattern? It seems unlikely that we should revert back to var self = this