美文网首页
LazyLoad懒加载报错TypeError undefined

LazyLoad懒加载报错TypeError undefined

作者: 日知一智 | 来源:发表于2018-08-29 16:33 被阅读0次

    添加LazyLoad懒加载的时候报错

    按照官方文档添加了懒加载,运行时报错

    TypeError undefined is not a function....
    

    具体报错内容和
    https://github.com/angular/angular-cli/issues/9825
    https://github.com/angular/angular-cli/issues/9488
    这两个帖子一致。

    // app-routing.module.ts
    import { NgModule } from '@angular/core';
    import { Routes, RouterModule, PreloadAllModules } from '@angular/router';
    import { AuthGuard } from './core/services/auth-guard.service';
    
    const routes: Routes = [
      { path: '', redirectTo: 'kanban', pathMatch: 'full' },
      { path: 'login', component: LoginComponent },
      {
        path: 'setting',
        canActivate: [AuthGuard],
        loadChildren: './setting/setting.module#SettingModule'
      }
    ];
    
    @NgModule({
      imports: [
        RouterModule.forRoot(routes, {
          preloadingStrategy: PreloadAllModules
        })
      ],
      exports: [RouterModule]
    })
    export class AppRoutingModule {}
    
    
    // app.module.ts
    @NgModule({
      declarations: [
        AppComponent
      ],
      imports: [
        FormsModule,
        PopupModule,
        CoreModule,
        PipeModule,
        SettingModule,
        AppRoutingModule
      ],
      bootstrap: [AppComponent]
    })
    export class AppModule {}
    

    尝试解决方案一

    看帖子,有人说把loadChildren的值存在一个export出来的常量中就可以了。并且在JIT 和 AOT 都可以运行。
    听起来很神奇,但是抱着试一试的态度尝试了,失败。

    export const home = 'app/features/home/home.module#HomeModule';
    export const user = 'app/features/user/user.module#UserModule';
    
    export const routes: Routes = [
      {
        path: '',
        pathMatch: 'full',
        redirectTo: 'home'
      },
      {
        path: 'home',
        loadChildren: home
      },
      {
        path: 'user',
        loadChildren: user
      },
      {
        path: '**',
        redirectTo: 'home'
      }
    ];
    

    尝试解决方案二

    帖子中又有人提供了一个解决方案,使用引入module的方式。尝试了一下,可以work,但是好像有点不对劲的地方,仔细查看文档并且测试以后才发现,这是个假的懒加载。它确实解决了报错的问题,但是懒加载也没了。
    【注意】要使用懒加载,必须是lazy module的路径(字符串)。

    import { Awesome } from './awesome/awesome.module';
    //并且修改loadChildren
    loadChildren: () => Awesome
    

    尝试解决方案三

    把启动方式改成
    ng server --aot
    不报错,也确实是懒加载,但是速度慢

    尝试解决方案四

    把懒加载模块从app.module.ts中删除,终于解决了。
    还是ng server启动,速度不慢,没有报错

    // app.module.ts
    @NgModule({
      declarations: [
        AppComponent
      ],
      imports: [
        FormsModule,
        // 非懒加载模块
        PopupModule,
        CoreModule,
        PipeModule,
        // 懒加载模块
        // SettingModule,
        AppRoutingModule
      ],
      bootstrap: [AppComponent]
    })
    export class AppModule {}
    

    相关文章

      网友评论

          本文标题:LazyLoad懒加载报错TypeError undefined

          本文链接:https://www.haomeiwen.com/subject/qaxxdftx.html