I'm trying to protect authenticated routes using AuthGuard middleware. When I implement this middleware into a route. Those routes doesn't work after I activate guard.
App routing module
const routes: Routes = [
{
path: 'posts',
canLoad: [AuthGuardMiddleware],
loadChildren: () => import('./modules/posts/posts.module').then(m => m.PostsModule)
},
{
path: 'users',
canLoad: [AuthGuardMiddleware],
loadChildren: () => import('./modules/users/users.module').then(m => m.UsersModule)
}
];
@NgModule({
imports: [RouterModule.forRoot(routes, {
preloadingStrategy: PreloadAllModules
})],
exports: [RouterModule]
})
and AuthGuardMiddleware
@Injectable({
providedIn: 'root'
})
export class AuthGuardMiddleware implements CanActivate, CanLoad {
constructor(private authService: AuthService, private router: Router) {
}
canActivate(
route: ActivatedRouteSnapshot,
state: RouterStateSnapshot
): Observable<boolean | UrlTree> {
return this.authService.user.pipe(map(user => {
if (user) {
return true;
}
return this.router.createUrlTree(['/login']);
}));
}
canLoad(route: Route, segments: UrlSegment[]): Observable<boolean> | Promise<boolean> | boolean {
return this.authService.user.pipe(map(user => {
if (user) {
return true;
}
this.router.navigate(['/']);
return false;
}));
}
}
How can I fix it ? Note: AuthService::user type is BehaviorSubject initialized as null
UPDATE
I realized that when I clean up my app component and remove conditional router outlet, everything start to work fine. I still don't know what exactly causing this error.
app component
export class AppComponent implements OnInit {
currentUrl: string;
isAuthRoute = false;
constructor(private router: Router) {
}
ngOnInit() {
this.router.events.subscribe(event => {
if (event instanceof NavigationEnd) {
this.currentUrl = event.url;
this.isAuthRoute = ['/login', '/register']
.indexOf(this.currentUrl) !== -1;
}
});
}
}
app component view
<div *ngIf="!isAuthRoute">
<div class="row page-wrapper">
<div class="col-md-3 col-md-pull-9">
<app-sidebar></app-sidebar>
</div>
<div class="col-md-9 col-md-push-3 content-area">
<router-outlet></router-outlet>
</div>
</div>
</div>
<div style="height: 80vh" class="d-flex justify-content-center align-items-center" *ngIf="isAuthRoute">
<router-outlet ></router-outlet>
</div>
router-outletneeds to be there from the beginning? I've heard of an issue like that with angular-dart. But... before jumping to this conclusion try adding an extra module that would work as a shell for all the rest of your app and would be loaded/activated only for authorized users. It would be equivalent to your*ngIflogic. - julianobrasilrouter-outlet. - julianobrasil