Angular 6 - NavigationCancel - reason: "guard of the route returned false" - before guard even finished

Jana

I've got routes with lazy loading and onLoad Guard. Within the guard I grap the navigation menu from backend (you only see naviagtion points which you are authenticated for) and compare the route with the route-list from backend.

The problem: when I click on a button to a route, the route is triggered, but gets immediately canceled (traced in console) with the following reason:

NavigationCancelingError: Cannot load children because the guard 
of the route "path: 'meldungsmanagement'" returned false

although debugging angular shows that the onLoad method didn't even resolve - and it would return true!

appRouting.module.ts

import {NgModule} from '@angular/core';
import {PortalComponent} from './portal/portal.component';
import {AuthGuardService} from './core/authguard.service';
import {RouterModule, Routes} from '@angular/router';

const appRoutes: Routes = [
    {
        path: '',
        redirectTo: 'startseite',
        pathMatch: 'full'
    },
    {
        path: 'startseite',
        component: PortalComponent
    },
    {
        path: 'meldungsmanagement',
        loadChildren: './incidents/incidentOverview.module#IncidentOverviewModule',
        canLoad: [AuthGuardService]
    },

];

@NgModule({
    imports: [RouterModule.forRoot(
        appRoutes,
        {enableTracing: true})], // enable only for debugging purposes
    exports: [RouterModule]
})
export class AppRoutingModule {
}

AuthGuardService:

import {Injectable} from '@angular/core';
import {
    ActivatedRouteSnapshot,
    CanActivate,
    CanLoad,
    Route,
    Router,
    RouterStateSnapshot,
    UrlSegment
} from '@angular/router';
import {GlobalSettingsService} from './globalSettings.service';
import {Observable} from 'rxjs';
import {NavbarService} from './navbar.service';
import {NavbarModel} from '../shared/models/navbar.model';
import {KeycloakService} from './keycloak/keycloak.service';

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

    constructor(private router: Router,
                private keycloakService: KeycloakService,
                private navBarService: NavbarService,
                private globalSettings: GlobalSettingsService) {
    }

    canLoad(route: Route,
            segments: UrlSegment[]): Observable<boolean> | Promise<boolean> | boolean {

        const isLoggedIn = this.keycloakService.isAuthenticated();
        if (isLoggedIn) {

            this.navBarService.getStucture().subscribe(menuRoutes => {                    
                    const isAccessAllowed: boolean = this.checkRoleAccessAllowed(segments, menuRoutes);
                    console.log('AuthGuard.canLoad() - return ' + isAccessAllowed + ' for route ' + route.path);
                    return Promise.resolve(isAccessAllowed);
                }
            );
        } else {
            console.log('AuthGuard.canLoad() - return false (not loggedIn) for route ' + route.path);
            return Promise.resolve(false);
        }
    }

    checkRoleAccessAllowed(url: UrlSegment[], menu: Array<NavbarModel>): boolean {
        const foundNavbarModel: NavbarModel = menu.find(value => value.link.indexOf(url[0].path) > -1);
        if (foundNavbarModel) {
            return true;
        } else {
            return false;
        }
    }
}

console output: (traced from clicking button to route "meldungsmanagement" on)

 Router Event: NavigationStart
 NavigationStart(id: 3, url: '/meldungsmanagement')
 NavigationStart {id: 3, url: "/meldungsmanagement", navigationTrigger: "imperative", restoredState: null}
 Router Event: NavigationCancel
 NavigationCancel(id: 3, url: '/meldungsmanagement')
 NavigationCancel {id: 3, url: "/meldungsmanagement", reason: "NavigationCancelingError: Cannot load children bec…route "path: 'meldungsmanagement'" returned false"}id: 3reason: "NavigationCancelingError: Cannot load children because the guard of the route "path: 'meldungsmanagement'" returned false"url: "/meldungsmanagement"__proto__: RouterEvent
 Router Event: NavigationStart
 NavigationStart(id: 4, url: '/')
 NavigationStart {id: 4, url: "/", navigationTrigger: "imperative", restoredState: null}
 Router Event: RoutesRecognized
 Router Event: GuardsCheckStart
 Router Event: GuardsCheckEnd
 Router Event: ActivationEnd
 Router Event: ChildActivationEnd
 Router Event: NavigationEnd
 Router Event: Scroll
 Router Event: NavigationStart
 NavigationStart(id: 5, url: '/')
 NavigationStart {id: 5, url: "/", navigationTrigger: "imperative", restoredState: null}
 AuthGuard.canLoad() - return true for route meldungsmanagement
 Router Event: RoutesRecognized
 RoutesRecognized(id: 5, url: '/', urlAfterRedirects: '/startseite', state: Route(url:'', path:'') { Route(url:'startseite', path:'startseite') } )
 RoutesRecognized {id: 5, url: "/", urlAfterRedirects: "/startseite", state: RouterStateSnapshot}
 Router Event: GuardsCheckStart
 GuardsCheckStart(id: 5, url: '/', urlAfterRedirects: '/startseite', state: Route(url:'', path:'') { Route(url:'startseite', path:'startseite') } )
 GuardsCheckStart {id: 5, url: "/", urlAfterRedirects: "/startseite", state: RouterStateSnapshot}
 Router Event: ChildActivationStart
 ChildActivationStart(path: '')

As you can see, the route is triggered, closed, redirected to "/" and many rows later the authGuard says he returnd TRUE...

Why on earth does the router not wait for the guards answer? Where does the "false" come from? Where did I go wrong?

I'd appreciate any help, thanks!

PS: I already read the question Angular2: Router Event: NavigationCancel before Route Guard has resolved but it didn't match my case, cause the user still is logged in and I don't want to redirect within the guard.

user4676340

Following my comments, here is a way of returning the value you want to :

if (isLoggedIn) {
  return this.navBarService.getStucture().pipe(
    map(menuRoutes => this.checkRoleAccessAllowed(segments, menuRoutes)),
    tap(value => console.log('AuthGuard.canLoad() - return ' + value + ' for route ' + route.path))
  );
}

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related