Assuming Return false will be returned on authentication either on http call but for now i am returning false from CanLoadChildren() Method Inorder to test canLoad But despite of calling canLoad and returning false canLoad still loads Module and redirect to that module.can any one help ? Thanks

AuthService

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

@Injectable()
export class AuthService {

    constructor() {}

    public CanLoadChildren(): boolean {

        return false;
    }

}

Auth Guard File

import {
    AuthService
} from './auth.service';

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

import {
    CanActivate,
    CanLoad,
    Route,
    ActivatedRouteSnapshot,
    RouterStateSnapshot,
    Router
} from '@angular/router';


@Injectable()
export class CanActivateViaAuthGuardService implements CanActivate, CanLoad {

    constructor(private _authService: AuthService, private router: Router) {}

    canLoad(route: Route): boolean {

        console.log("Can Load Childrens Called");
        console.log(route);
        this.router.navigate(['/Domains']);
        return this._authService.CanLoadChildren();
    }
}

app.router.ts

export const APPROUTES: Routes = [

    {
        path: 'User',

        canLoad: [CanActivateViaAuthGuardService],

        loadChildren: 'app/LazyAdminConsoleModule'
    }

]
1

There are 1 best solutions below

0
Selene Blok On

You could try this:
By moving the this.router.navigate() into your canLoad function you should be able to verify authentication like this: Auth == true -> Route to /domains

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

@Injectable()
export class AuthService {

    constructor() { }

    public CanLoadChildren(): boolean {
        return false;
    }

}

//Auth Guard
import { AuthService } from './auth.service';
import { Injectable } from '@angular/core';
import { CanActivate, CanLoad, Route, ActivatedRouteSnapshot, RouterStateSnapshot, Router } from '@angular/router';

@Injectable()
export class CanActivateViaAuthGuardService implements CanActivate, CanLoad {

    constructor(private _authService: AuthService, private router: Router) { }

    canLoad(route: Route): boolean {
        /*Put this inside of your function*/
        if (this._authService.CanLoadChildren() === true) {
            this.router.navigate(['/Domains']);
        } else {
            this.router.navigate(['/'])//HomepageLink here
        }
    }
}

//App Router
export const APPROUTES: Routes = [
    {
        path: 'User', canLoad: [CanActivateViaAuthGuardService], loadChildren: 'app/LazyAdminConsoleModule'
    }
]