延迟加载功能模块无法正常工作

时间:2018-06-12 18:46:15

标签: angular angular-ui-router angular4-router

我有一个app.routing.ts文件,如下所示

    import { ModuleWithProviders, NgModule } from '@angular/core';
    import { Routes, RouterModule } from '@angular/router';
    import { AppComponent } from './app.component';
    import { SalesComponent } from './advisory/sales.component';

    const appRoutes: Routes = [
        {
            path:'admin',loadChildren:'app/auth/admin/admin.module#AdminModule'
        },
        {
            path: '',
            redirectTo: '/main',
            pathMatch: 'full'
        },
        {
            path: 'main', component: SalesComponent,
            data: { apptitle: 'main', subtitle: 'main' }
        },

    ];

@NgModule({
    imports: [RouterModule.forRoot(appRoutes, 
        { useHash: true },
        )],
    exports: [RouterModule]
})

export class AppRoutingModule { }

功能模块admin.module.ts文件如下

 import { NgModule } from '@angular/core';
    import { CommonModule } from '@angular/common';
    import { AdminComponent } from './admin.component';
    import { RouterModule } from '@angular/router';

    @NgModule({
      imports: [
    CommonModule,
    RouterModule.forChild([{
    path: '',
    component: AdminComponent,
    }
    ]),

    declarations: [AdminComponent]
    })

    export class AdminModule { }

如果我在浏览器中点击localhost:4200 /#/ main,它可以工作,但如果我输入localhost:4200 /#/ admin或localhost:4200 / admin-它会刷新并加载相同的主页面。知道为什么会发生这种情况并提出任何建议吗?

2 个答案:

答案 0 :(得分:0)

我猜路径错了,你应该改用相对路径,

 path:'admin',loadChildren:'./auth/admin/admin.module#AdminModule'

答案 1 :(得分:0)

这是一个StackBlitz,它工作https://stackblitz.com/edit/angular-f568ym?file=src%2Fapp%2Fapp.component.html

您应该使用相对路径。

path:'admin',loadChildren:'./auth/admin/admin.module#AdminModule'

此外,您可能会遇到AdminModule

中定义的路线问题

我会将AdminModule中的语法更改为:

import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { AdminComponent } from './admin.component';
import { RouterModule } from '@angular/router';

const adminRoutes: Routes = [
  {
      path:'',
      component:AdminComponent,
      pathMatch: 'full'
  }
];

@NgModule({
  imports: [
    CommonModule,
    RouterModule.forChild(adminRoutes)
  ],
  declarations: [AdminComponent]
})

export class AdminModule { }