Search code examples
angularangular-routingangular-router-guards

Unable to router.navigate to lazy loaded child modules


I'm new to angular. I am starting with the latest version, 8.

I am trying to write an app. The initial state of the route is path:'' and I would like to determine the next route based on some condition in the base path here. If the condition is true, I need to redirect the user to /home and if it fails, I need to redirect to /welcome. Both home and welcome are lazily loaded.

I have a guard service where the routing decision is made (which path to take).

app-routing.ts

import { Routes, RouterModule } from '@angular/router'; 
import { HomeGuardService } from './services/route-guard/home-guard.service';


const routes: Routes = 
[ 
    { 
        path: '', pathMatch: 'full', 
        canActivate: [HomeGuardService], 
        children: 
        [ 
            { path: 'welcome', loadChildren: () => import('./welcome/welcome.module').then(mod => mod.WelcomeModule), }, 
            { path: 'home', loadChildren: () => import('./home/home.module').then(mod => mod.HomeModule) } 
        ] 
    } 
]; 

@NgModule({ imports: [RouterModule.forRoot(routes)], exports: [RouterModule] }) 
export class AppRoutingModule { }

home-guard.service.ts

import { ActivatedRouteSnapshot, RouterStateSnapshot } from '@angular/router/src/router_state'; 
import { LocalStorageService } from '../storage/local-storage.service'; 

@Injectable({ providedIn: 'root' }) 
export class HomeGuardService implements CanActivate { 

    constructor( private router: Router) { } 

    canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) { return this.checkCountrySelection(state); } 


    private checkCountrySelection(state: RouterStateSnapshot): boolean { 
        if (<my_condition>) { 
            this.router.navigate(['home']); 
            return true; 
        } 
        this.router.navigateByUrl('welcome'); 
        return false; 
    } 
}

Now, with this setup, angular complains that it cannot match any routes for URL Segment: 'welcome'

(Initially, I have made the condition to fail in home-guard service to it would load the welcome module)


Solution

  • You can't define children to the default path, you can change your routes array to :

    const routes: Routes = 
    [ 
      { 
        path: 'welcome',
        canActivate: [HomeGuardService],
        loadChildren: () => import('./welcome/welcome.module').then(mod => mod.WelcomeModule)
      },
      { 
        path: 'home',
        canActivate: [HomeGuardService],
        loadChildren: () => import('./home/home.module').then(mod => mod.HomeModule)
      }
      ...