So there a couple things wrong here but I don't think the promise is one of them. Your function signature says that you have the option to return one of three types,
canActivate(): boolean | Observable<boolean> | Promise<boolean>
But you only ever return a boolean, so really you could re-write this as just,
canActivate(): boolean
But that isn't the issue. It is hard to say without seeing your route setup, but it looks like you are re-routing the user if the route they are requesting is allowed and that isn't necessary. Route guards run when the user is already trying to navigate to a page. If the route guard returns true, that navigation is allowed to happen and the user will proceed to whatever page the route guard is protecting.
But you should be specifying the re-direct page when the route guard returns false. In other words, when the user cannot access the page behind the guard, where do you want to send them?
In general, that would look something like this,
@Injectable()
export class AuthGuard implements CanActivate {
constructor(private router: Router) {}
canActivate(state: RouterStateSnapshot): boolean {
if (!this.localStorage.getObject('isInitialized')) {
//No need to route here, user will be taken to the route they were trying access
return true;
} else {
//Send the user back to the '/anotherpage' path if they are not logged in
this.router.navigate(['/anotherpage']);
return false;
}
}
}
Then define your routes somewhere like this,
export const appRoutes: Routes = [
{
path: 'pageProtectedByAuthGuard',
component: YourComponent,
canActivate: [AuthGuard]
}
];
Then in your module you need to import those routes,
@NgModule({
imports: [RouterModule.forRoot(appRoutes, { enableTracing: false })],
...
})
More on CanActivate here: https://angular.io/api/router/CanActivate