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

时间:2019-06-04 07:30:03

标签: angular angular-routing angular-router-guards

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

我正在尝试编写一个应用程序。路由的初始状态为path:'',我想根据此处基本路径中的某些条件确定下一条路由。如果条件为true,则需要将用户重定向到/ 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 { }

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

现在,使用此设置,angular抱怨它不能匹配URL段“欢迎”的任何路由

(起初,我已将条件设置为在家庭警卫服务中失败,因为它将加载欢迎模块)

2 个答案:

答案 0 :(得分:1)

您的路线是被守卫的孩子。

万一它不跟您说话:如果您由于守卫而无法访问该网上论坛,那么您将由于守卫而无法访问这些孩子

对于每个路由深度,都会运行警卫,并且如果一个失败并重定向,将无法访问以下路由。

您必须将自己的路线从受保护的路线中删除才能使其正常运行。

答案 1 :(得分:1)

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

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)
  }
  ...
相关问题