angular2路由器延迟加载不注入组件

时间:2016-11-20 16:45:48

标签: angular angular2-routing

我正在尝试使用路由器进行延迟加载angular2模块,如英雄教程中所示。在我的网络选项卡中,我可以看到文件正在我的浏览器中下载,但该组件未显示在我的浏览器中

//module
@NgModule({
  declarations: [
    CustomerDashboardComponent
  ],
  exports: [
    CustomerDashboardComponent
  ]
})
export class CustomerDashboardModule {
}

//component code
@Component({
  selector: 'customer-dashboard',
  templateUrl: 'customer-dashboard/customer-dashboard.html',
})
export class CustomerDashboardComponent extends OnInit{

  constructor(private router: Router,
              private homeService: HomeService,
              private restService: RestService
  ) {
  }
}

1 个答案:

答案 0 :(得分:1)

我没有看到您的路由器代码从延迟加载的模块加载您的组件。使用loadChildren加载模块后,模块应该有一个默认路由选项来加载组件。在延迟加载的模块中添加默认路由,如下所示

//router code
loadChildren: 'src/customer-dashboard/customer-dashboard.module#CustomerDashboardModule'

//default routing definition code
const routes: Routes = [
  { path: '', component: CustomerDashboardComponent }
];
export const routing: ModuleWithProviders = RouterModule.forChild(routes);

//routing import in module
@NgModule({
  imports: [
    routing
  ],
  declarations: [
    CustomerDashboardComponent
  ],
  exports: [
    CustomerDashboardComponent
  ]
})
export class CustomerDashboardModule {
}

//component code
@Component({
  selector: 'customer-dashboard',
  templateUrl: 'customer-dashboard/customer-dashboard.html',
})
export class CustomerDashboardComponent extends OnInit{

  constructor(private router: Router,
              private homeService: HomeService,
              private restService: RestService
  ) {
  }
}