I performed the composition of my CanActivate and CanLoad through the class LoggedInGuard. The problem is that whenever I refresh the page, I'm redirected to the Login page, even logged in. Below my LoggedInGuard class
@Injectable()
export class LoggedInGuard implements CanLoad, CanActivate {
constructor(private signinService: SigninService, private router: Router) { }
checkAuthentication(path: string): boolean {
const loggedin = this.signinService.isLoggedin();
if (!loggedin) {
this.router.navigate([ this.signinService.handleLogin('/${ path }') ]);
}
return loggedin;
}
canLoad(route: Route): boolean {
return this.checkAuthentication(route.path);
}
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
return this.checkAuthentication(route.routeConfig.path);
}
}
My SignService:
@Injectable({
providedIn: 'root'
})
export class SigninService {
private baseUrl: string;
private user: User;
private lastUrl: string;
constructor(private http: HttpClient, private router: Router) {
this.baseUrl = '${environment.url}/auth/signin';
this.router.events
.filter(e => e instanceof NavigationEnd)
.subscribe((e: NavigationEnd) => this.lastUrl = e.url);
}
public isLoggedin(): boolean {
return this.user !== undefined && localStorage.getItem('token') !== undefined;
}
public login(username: string, password: string): Observable<User> {
const params = new HttpParams()
.set('username', username)
.set('password', password);
return this.http.post<User>('${this.baseUrl}', params).do((user: User) => this.user = user);
}
public logout(): void {
localStorage.clear();
this.user = undefined;
this.handleLogin('/');
}
public handleLogin(path: string = this.lastUrl) {
this.router.navigate(['/signin', btoa(path)]);
}
public get UserDetail(): User {
return this.user;
}
}
The Services are set within the responsibility providers. In my SigninComponent and I log in as follows:
public login(): void {
console.log(this.signinForm);
this.signinService.login(this.signinForm.value.username, this.signinForm.value.password ).subscribe((user: User) => {
this.user = user;
localStorage.setItem('token', this.user.token.token);
this.isSuccess = true;
this.message = 'Usuário encontrado. Aguarde um momento!';
}, (err: HttpErrorResponse) => {
this.isSuccess = false;
this.message = err.error.error.message;
console.error(err);
}, () => {
this.router.navigate([ atob(this.navigateTo) ]);
});
}