无法 router.navigate 延迟加载子模块

Unable to router.navigate to lazy loaded child modules

我是 angular 的新手。我从最新版本 8 开始。

我正在尝试编写一个应用程序。路线的初始状态是 path:'' 我想根据此处基本路径中的某些条件确定下一条路线。如果条件为真,我需要将用户重定向到 /home,如果失败,我需要重定向到 /welcome。 home 和 welcome 都是延迟加载的。

我有一个警卫服务,可以在其中做出路由决定(选择哪条路径)。

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 { }

首页-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; 
    } 
}

现在,使用此设置,angular 抱怨它无法匹配 URL 段的任何路由:'welcome'

(最初,我设置了家庭卫士服务失败的条件,它会加载欢迎模块)

您的路线 children 属于受保护组。

万一它不跟你说话 : 如果你因为看守不能进群,你将不能进children因为守卫

守卫是运行 每条路线深度,如果一个失败并重定向,将无法到达以下路线。

您必须将您的路线从受保护的路线上移开才能使其正常工作。

您不能将子项定义为默认路径,您可以将路由数组更改为:

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)
  }
  ...