Firstly, I am not sure that this is the best way to handle this problem, but what I am looking for is a route guard on "/" which checks if the user is logged in, if so to redirect them to "/dashboard". I would like to do this before the route is loaded, to avoid a screen flashing since were checking auth status on a remote server.
I am implementing the canActivate interface, but its not working as expected. It hits the auth service, and returns the user, which according to this test code should redirect the user, but instead I am seeing the user in the console but no redirect.
Here is the code
import { Injectable } from '@angular/core';
import { Router, CanActivate } from '@angular/router';
import { Observable } from 'rxjs/Observable';
import { User } from './../../models/user.model';
import { AuthService } from './auth.service';
@Injectable()
export class HomeAuthGuard implements CanActivate {
constructor(
private router: Router,
private authService: AuthService
) {}
canActivate(): Promise<boolean> {
return new Promise((resolve) => {
this.authService.getStatus()
.then(function (user: User) {
console.log('home auth', user)
this.router.navigate(['/dashboard']);
resolve(false);
})
.catch(function () {
resolve(true);
});
});
}
}
The canActivate has to return true to access the page. If it returns false, we can not access the page. We can write our user authorization and authentication logic inside the canActivate function. AuthGuard is used to protect the routes from unauthorized access.
CanActivateChild - Decides if children routes of a route can be activated. CanDeactivate - Decides if a route can be deactivated.
CanActivatelink If any guard returns false , navigation is cancelled. If any guard returns a UrlTree , the current navigation is cancelled and a new navigation begins to the UrlTree returned from the guard.
The service injects AuthService and Router and has a single method called canActivate . This method is necessary to properly implement the CanActivate interface. The canActivate method returns a boolean indicating whether or not navigation to a route should be allowed.
This is happen because of 'this' binding. Mostly likely your code goes to catch block after console.log due to fact that 'this' is not your component class instance. Use "fat arrow" to solve this issue. like:
return new Promise((resolve) => {
this.authService.getStatus()
.then((user: User) => {
console.log('home auth', user)
this.router.navigate(['/dashboard']);
resolve(false);
})
.catch(err => {
resolve(true);
});
})
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With