Currently, I am utilizing Angular2 along with Typescript. Let's assume that there is a dummy login component and an authentication service responsible for token authentication. In one of the map functions, I intend to set the variable authenticated
as soon as the token is received from the backend server.
The dilemma I am facing is that I am unable to access the instance variable within the chaining function. The this
inside the chaining function actually refers to the subscriber of this observable. Although I understand that this issue stems from scope problems, finding a solution has proven to be challenging.
export class AuthenticationService {
authenticated:boolean = false; //the desired variable to be accessed
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; //where I aim to access the instance variable
sessionStorage.setItem('auth_token', res.token);
}
return res;
});
}
The dummy-login component where the aforementioned login()
method is invoked appears as follows:
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']);
}
})
}
}