When my scenario requires authentication/login of a Windows user upon route activation, I need to check if the user is authenticated. If not, I make a call to the server to generate a token and expect it to return true in order to activate the route. However, this process does not seem to work as intended.
Here's a snippet of code:
auth.guard.ts
import { Observable } from 'rxjs/Observable';
import { CanActivate, Router, ActivatedRouteSnapshot } from '@angular/router';
import { Injectable } from '@angular/core';
import { AuthService } from './../data/auth.service';
import { TokenService } from '../auth/token.service';
import { of } from 'rxjs/observable/of';
@Injectable()
export class AuthGuard implements CanActivate {
constructor(
private loginService: AuthService,
private tokenService: TokenService,
private router: Router) {
}
canActivate(route: ActivatedRouteSnapshot): Observable<boolean> {
const operation = route.data.operation;
if (!this.tokenService.isAuthenticated() && !this.login()) {
console.log('canActive1: ', false);
return of(false);
}
console.log('canActive: ', true);
return of(true);
}
login() {
this.loginService.getToken().subscribe((user) => {
console.log('token returned..');
if (user && user.token) {
this.tokenService.storeToken(user.token);
return true;
}
return false;
});
}
}
Console:
- canActivate1: false
- token returned..