【问题标题】:How do you lazy load a single component in Angular2 (RC5)你如何在Angular2(RC5)中延迟加载单个组件
【发布时间】:2016-08-15 22:21:21
【问题描述】:

我已经能够使用 Route 的规定 loadChildren 属性让延迟加载与 NgModules 一起工作。

import {RouterModule} from ‘@angular/router’
import {NgModule} from ‘@angular/core’
@NgModule({
  declarations: [ MyComponent, MyHomeRoute ],
  bootstrap: [ MyComponent ],
  imports: [
     RouterModule.forRoot([
     { path: ‘home’, component: MyHomeRoute },
     { path: ‘lazy’, loadChildren: ‘./my-lazy-module’ }
  ])
})
class MyAppModule {}

但是有没有办法使用“组件”属性的字符串来配置路由以延迟加载单个组件(而不是 NgModule)?

我总是遇到如下错误:
“Cannot resolve component using 'lazyComponent'”

【问题讨论】:

  • 您可以将组件移动到自己的模块中。
  • 嗯……我知道。如果它只是包装一个组件,它似乎更不必要的“样板化”。你是说这是唯一的方法吗?因为我看到 Route 的“组件”属性被允许是一个字符串,所以看起来可能有延迟加载组件的意图。
  • 这是 RC.5 之前的方式。我不知道这样是否仍然应该工作。
  • 嗨,你有答案了吗?

标签: angular angular2-routing


【解决方案1】:
@NgModule({
  imports:      [ BrowserModule, routing ],
  declarations: [ AppComponent ],
  bootstrap:    [ AppComponent ]
})
export class AppModule { }

然后按需加载:

import { Routes, RouterModule } from '@angular/router'; 
 const routes: Routes= [{path: 'welcome', loadChildren: 'app/screens/welcome.module'}];
export const routing = RouterModule.forRoot(routes);

这里:loadChildren: 'app/screens/welcome.module' 是 ts 文件 app/screens/welcome.module.ts

更详细的例子,检查这个:http://plnkr.co/edit/18CZVF?p=preview

【讨论】:

  • @GunterZochbauer 推荐的相同解决方案。
  • Plunkr 文件在单击其中的链接时不执行任何操作
猜你喜欢
  • 1970-01-01
  • 2016-12-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-12-10
  • 1970-01-01
  • 2020-10-17
  • 1970-01-01
相关资源
最近更新 更多