1
votes

I'm trying to use the Angular router, and I'm having an issue on the empty path . Here's my routes:

const routes: Routes = [

    { path: 'feed', loadChildren: './feed/feed.module#FeedModule', canLoad: [AuthGuardService] },
    { path: 'login', component: LoginPage },
    { path: 'register', component: RegisterPage },
    { path: '', redirectTo: '/feed', pathMatch: 'full' },
    { path: '**', redirectTo: '/' }
];

My AuthGuardService has a method canLoad which always returns false and redirects to the '/login' path :

...
@Injectable()
export class AuthGuardService implements CanLoad {
  constructor(private router: Router) {
  }
  canLoad(route: Route): boolean {

    this.router.navigate([ '/login' ]);
    return false;
  }
}

When I go to 'localhost:4200/feed', I'm redirected to '/login'.

But if I go to 'localhost:4200/', the auth guard is ignored and the components of my feed module are displayed.

Do you have any idea why ?

Thanks !

2
Does it work if you change canLoad to canActivate? - DeborahK

2 Answers

0
votes

I have a working code in my scenario. Check this, if it can help you.

Instead of canLoad, you can use canActivate.

canActivate is used to prevent an unauthorized user
canLoad is used to prevent the entire module of app

in below example you can replace canActivate with canLoad, if you wish to use canLoad instead.

import { Injectable } from '@angular/core';
import { Router, CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot } from '@angular/router';

@Injectable()
export class AuthGuard implements CanActivate {

    constructor(private router: Router) { }

    canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
        if (localStorage.getItem('currentUser')) {
            // logged in so return true
            return true;
        }

        // not logged in so redirect to login page with the return url
        this.router.navigate(['/login'], { queryParams: { returnUrl: state.url }});
        return false;
    }
}

and while writing routes, you can define like below.

{ path: 'newLeaveRequest', component: NewLeaveRequestComponent, canActivate: [AuthGuard]},
{ path: 'pastLeaveRequests', component: PastLeaveRequestComponent, canActivate: [AuthGuard]},

In app.module.ts Define AuthGuard in providers.

0
votes

I've solved my issue, sorry for the delay : I needed to use a component and to use canActivate in order to load the child module

{
    path: 'feed',
    canActivate: [ AuthGuard ],
    component: FeedComponent,
    children: [
        {
      path: '',
      loadChildren: () => FeedModule
}]}

Lazy loading for children works as well !

Cheers !