I'm using Angular2 with Typescript. Say I have a dummy login component and an authentication service to do token authentication. I'm going to set the authenticated variable in one of the map function as soon as I get the token from backend server.
The question is that I can't access the instance variable inside the chaining function. The this inside the chaining function is actually the subscriber of this observable. I know this's a scope issue but can't figure it out.
export class AuthenticationService {
authenticated:boolean = false; //this is the variable I want to access
constructor(public http: Http) {
this.authenticated = !!sessionStorage.getItem('auth_token');
}
login(username, password) {
let headers = new Headers();
headers.append('Content-Type', 'application/json');
return this.http
.post(
'http://localhost:8080/token-auth',
JSON.stringify({ username, password }),
{ headers }
)
.map(res => res.json())
.map((res) => {
if (res) {
this.authenticated = true; //this is where I want to access the instance variable
sessionStorage.setItem('auth_token', res.token);
}
return res;
});
}
The dummy-login component where the above login() method is called is like this:
export class DummyLoginComponent {
constructor(private auth: AuthenticationService, private router: Router) {
}
onSubmit(username, password) {
this.auth.login(username, password).subscribe((result) => {
if (result) {
this.router.navigate(['Dashboard']);
}
})
}
}
authenticatedinstance variable to true inside the.map()function.login? Either fix that code, or makeloginan arrow functionthis.auth.authenticatedinDummyLoginComponent.