首页 > 解决方案 > Angular 5:不同模块中的不同路由器插座+延迟加载

问题描述

我有两个模块,每个模块在其 html 中都有一个路由模块文件和一个路由器插座。我想根据我所在的模块加载组件。

我的文件树如下所示:

project
|-- module2
|-- -- profil
|-- -- - profil.component.html 
|-- -- - profil.component.ts
|-- -- - profil.component.spec.ts
|-- -- - profil.component.css
|-- -- module2-routing.module.ts
|- module1-routing.module.ts
|- module1.module.ts
|- module1.component.ts
|- module1.component.spec.ts
|- module1.component.css

我有以下文件:

module1-routing.module.ts

import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { HomeComponent } from './home/home.component';

const routes: Routes = [
    { path: '', redirectTo: '/home', pathMatch: 'full' },
    { path: 'home', component: HomeComponent },
    { path: 'module2', loadChildren: './module2/module2.module#Module2Module' }
];

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

module1.component.html

<router-outlet name="m1"></router-outlet>

module2-routing.module.ts

import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';

import { HomeComponent } from './home/home.component';
import { ProfilComponent } from './profil/profil.component';

const routes: Routes = [
  { path: '', component: HomeComponent },
  { path: 'profil', component: ProfilComponent }
];

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

模块2/home.component.html

<div id="module2-home">

  <app-header></app-header>
  <router-outlet name='m2'></router-outlet>

</div>

我尝试在路由文件中使用 outlet 选项(例如:{ path: 'profil', component: ProfilComponent, outlet: 'm2' } ),但出现此错误:

ERROR Error: Uncaught (in promise): Error: Cannot match any routes. URL Segment: 'home'
Error: Cannot match any routes. URL Segment: 'home'

标签: angulartypescriptangular5

解决方案


// appRouting-routing.module.ts
        const routes: Routes = [
      { path: '', redirectTo: '/login', pathMatch: 'full' },
      { path: 'login', component: LoginComponent },
      { path: 'dashboard', component: DashboardComponent },
      {
        path: 'modules', component: ModulesComponent,
        children: [
          { path: 'module1', component: Module1Component, children: Module1_ROUTE },
          { path: 'module2', component: Module2Component, children: Module2_ROUTE }
        ]
      }
    ];


    //export your child routes from your module1 and module2 routing.ts files
    //example:
   export const Module1_ROUTE: Routes = [
        { path: '', redirectTo: '/home', pathMatch: 'full' },
        { path: 'home', component: HomeComponent }
    ];

参考子路线文档。这将解决您的问题。


推荐阅读