1

I'am using CanActivate feature for my router and its child, but it doesn't work - Have been using the same couple of months ago, but now not.

There is no error, warning or something similar I can debug... the app just run and I can reach the router I want to protect normal as all the other routes.

Could you please see what's wrong with the following code? The problem is that I even doesn't get any error.

As Info I'am using Angular 5.

app.router.ts:

export const router: Routes = [

    { path: '', redirectTo: 'home', pathMatch: 'full'},
    { path: 'home', component: HomeComponent},
    { path: 'signup', component: SignupComponent},
    { path: 'dashboard', canActivate: [ AuthguardGuard ],
            children:
            [
                { path: '', loadChildren: './dashboard/dashboard.module#DashboardModule', pathMatch: 'full' }
            ]
    },

    { path: '**', redirectTo: 'page-not-found' }

];

export const appRoutes: ModuleWithProviders = RouterModule.forRoot(router);

dashboard.module.ts:

const dashboardRoutes: Routes = [

    { path: 'user', redirectTo: 'user', pathMatch: 'full' },
    { path: 'user', component: UserComponent,
        children: [
            { path: '', component: EditComponent },
            { path: 'userMail', component: UserMailComponent },
            { path: 'userSettings', component: UserSettingsComponent}
        ]
    },
];

authguard.guard.ts:

import { Injectable } from '@angular/core';
import { CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot } from '@angular/router';
import { Observable } from 'rxjs/Observable';
import { AuthService } from './_service/auth.service';


@Injectable()
export class AuthguardGuard implements CanActivate {
    constructor( private user: AuthService ) {
        console.log('In AuthGuard!');
    }
    canActivate(
        next: ActivatedRouteSnapshot,
        state: RouterStateSnapshot): Observable<boolean> | Promise<boolean> | boolean {
        return this.user.isUserAuthenticated();

    }
}

auth.service.ts:

import { Injectable } from '@angular/core';

@Injectable()
export class AuthService {

    public isUserAuthenticated;
    private userName;

    constructor() {
        this.isUserAuthenticated = false;
    }

    setUserLoggedIn() {
        this.isUserAuthenticated = true;
    }

    getUserLoggedIn() {
        return this.isUserAuthenticated;
    }

}
k.vincent
  • 3,743
  • 8
  • 37
  • 74
  • on first sight, you're calling service as method `return this.user.isUserAuthenticated()` and you actually have a property in service. – dee zg Mar 16 '18 at 08:12
  • And this means? What would be the correct way to make it working as it was fine with the same concept couple of months ago? – k.vincent Mar 16 '18 at 08:16
  • i don't know if that's the problem, its just the first detail i've spotted. i would try calling that like: `return this.user.isUserAuthenticated` – dee zg Mar 16 '18 at 08:19
  • I'll check. Why am I being down voted? What's wrong with the question? – k.vincent Mar 16 '18 at 08:22
  • not sure. wasn't me. – dee zg Mar 16 '18 at 08:24
  • @deezg: But the service is being imported in `authguard.guard.ts`: `import { AuthService } from './_service/auth.service';`. It should be available/accessible – k.vincent Mar 16 '18 at 08:47
  • yes, i know. 1. remove `alert('In AuthGuard!');`. 2. replace `this.user.isUserAuthenticated()` with `console.log(this.user.isUserAuthenticated); this.user.isUserAuthenticated;` and let us know what you see in console for boolean value – dee zg Mar 16 '18 at 08:49
  • also, did you register your guard with your module? – dee zg Mar 16 '18 at 08:53
  • Yes, that's why I do have the alert/console.log there.. but I even don't get the alert. This whats strange. – k.vincent Mar 16 '18 at 08:54
  • Yes, I do. `providers: [ {provide: MAT_DIALOG_DATA, useValue: {}}, {provide: MatDialogRef, useValue: {}}, AuthService, AuthguardGuard ],` – k.vincent Mar 16 '18 at 08:55
  • try `ng serve --aot`. it might spit out some additional errors you might use as a guide – dee zg Mar 16 '18 at 08:57
  • I'am using `ng serve -aot` already – k.vincent Mar 16 '18 at 09:01
  • i think you might want to change `canActivate` to `canActivateChild` or use `canLoad` for lazy loaded module. You have no component on that route that should be activated and that's probably the reason why guard never gets triggered. ref: https://angular.io/guide/router#canactivatechild-guarding-child-routes – dee zg Mar 16 '18 at 09:24
  • @deezg: have been trying this... I think the cause might be somewhere else. – k.vincent Mar 16 '18 at 10:03
  • yes, obviously. please post a solution here when you find it. – dee zg Mar 16 '18 at 10:04
  • Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/166975/discussion-between-k-vincent-and-dee-zg). – k.vincent Mar 16 '18 at 15:20
  • @deezg: Issue fixed - added an answer. – k.vincent Mar 16 '18 at 15:21

1 Answers1

1

Issue solved... I removed this part from the app.router.ts:

{path: '', loadChildren: './dashboard/dashboard.module#DashboardModule', pathMatch: 'full'}

and use it as following:

export const router: Routes = [

    { path: '', redirectTo: 'home', pathMatch: 'full'},
    { path: 'home', component: HomeComponent},
    { path: 'signup', component: SignupComponent},
    { path: 'dashboard', canActivate: [ AuthguardGuard ],
        children:[
           { path: '', component: EditComponent },
           { path: 'userMail', component: UserMailComponent },
           { path: 'userSettings', component: UserSettingsComponent}
        ]
    },

    { path: '**', redirectTo: 'page-not-found' }
];
export const appRoutes: ModuleWithProviders = RouterModule.forRoot(router);

And I can reach the authguard.guard.ts file and I get the expected result straight forward.

k.vincent
  • 3,743
  • 8
  • 37
  • 74
  • how can i get specific `childRoute` out of AuthGuard for example: `userSettings`. keeping it as child but accessible without AuthGuard. – Najam Us Saqib Nov 15 '21 at 08:27
  • @NajamUsSaqib, depends on your whole concept. Could you pls. post some of your code for the router here. Would help to understand the concpet. – k.vincent Nov 15 '21 at 14:12
  • i have pretty much same routing and Solved this by make 2 routing with same parent. Example: with Guard `{ path: 'dashboard', canActivate: [ AuthguardGuard ], children:[ { path: '', component: EditComponent }, { path: 'userMail', component: UserMailComponent }, ] },` without Guard and `{ path: 'dashboard', children:[ { path: 'userSettings', component: UserSettingsComponent} ] },` – Najam Us Saqib Nov 15 '21 at 15:38