首页 > 解决方案 > 多模块程序无法正常工作

问题描述

我有一个多模块程序。路由模块是 AppModule,子模块是 AdminModule、EmployeeModule 和 HomeModule。对于每个模块,我都创建了一个同名的组件。

AppModule看起来是这样的:

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { RouterModule, Routes, NoPreloading } from '@angular/router';  


import { AppComponent } from './app.component';
import { HomeModule } from './home/home.module';

const routes: Routes =  [    
  { path: 'Home', loadChildren:'app/home/home.module#HomeModule' },  
  { path: 'Employee', loadChildren:'app/employee/employee.module#EmployeeModule' },
  { path: 'Admin', loadChildren:'app/admin/admin.module#AdminModule' },  

];  


@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    HomeModule,
    RouterModule.forRoot(routes, { useHash: false, preloadingStrategy: NoPreloading }), 
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

这就是其他 3 个模块内部的样子:

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


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

@NgModule({
  imports: [
    CommonModule
  ],
  declarations: [HomeComponent]
})
export class HomeModule { }

程序加载并无错误地工作。例如,当我单击Home时,url 更改为http://localhost:4200/Home,但我没有看到 employee.component.html 加载。我应该怎么做才能解决这个问题?

标签: angularmodulemulti-module

解决方案


请注意,HomeModule 中的路径路由设置为空字符串。这是因为 AppModule 路由中的路径已经设置为 Home,所以 HomeModule 路由中的这个路由,已经在 Home 上下文中了。此路由模块中的每条路由都是子路由。

import { Routes, RouterModule } from '@angular/router';
const routes: Routes = [  
  { path: '', component: HomeComponent },  
];  

@NgModule({
  imports: [
    CommonModule,
    RouterModule.forChild(routes)
  ],
  declarations: [HomeComponent]
})
export class HomeModule { }

推荐阅读