Angular 4延迟加载未加载模块

时间:2018-03-28 07:12:36

标签: angular

我在Angular 4中加载了一个模块,但Chrome Augury插件表示该模块未加载。我看到模板,但没有必要的数据。 我的app-routing.module.ts:

import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';

import { InvalidRequestComponent } from './components/invalid-request.component';
import { RoleResolver } from './services/role-resolver.service';
import { LoadingComponent } from './components/loading.component';
import { AuthResolver } from './services/auth-resolve.service';

const appRoutes: Routes = [
  { path: '', component: LoadingComponent, resolve: { RoleResolver } },
  { path: 'user', loadChildren: 'app/ROLE_USER/user.module#UserModule', resolve: { AuthResolver } },'app/ROLE_USER/user.module#UserModule', resolve: { AuthResolver } },
  { path: '**', component: InvalidRequestComponent }
];

@NgModule({
  imports: [
    RouterModule.forRoot(appRoutes),
  ],
  exports: [
    RouterModule
  ],
  providers: [
    RoleResolver
  ]
})
export class AppRoutingModule { }

我的user.module.ts:

import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { FormsModule } from '@angular/forms';

import { UserRoutingModule } from './user-routing.module';

import { UserComponent } from './user.component';
import { HeaderComponent } from './components/plan/header.component';
import { CompanyProfileComponent } from './components/plan/company-profile.component';
import { DataService } from './services/data.service';

@NgModule({
  declarations: [
    UserComponent,
    HeaderComponent,
    CompanyProfileComponent
  ],
  imports: [
    CommonModule,
    FormsModule,
    UserRoutingModule
  ],
  providers: [
    DataService
  ]
})
export class UserModule { }

登录时,Augury显示: Augury

然后在刷新页面后显示正确的内容: Augury correct

NB!我知道Augury也会显示其他组件,但即使没有这些组件,它也无法正常工作,为了这个演示,我从上面的代码中删除了它们。

需要延迟加载,因为用户模块中的组件非常大,因此只应在登录时加载。

这个问题哪里可以说谎?可能是Angular 4的加载顺序吗?

我想我已经尝试过所有我发现但尚未成功的事情。有趣的是,一切似乎都适用于Firefox,但问题出现在Chrome中(不是每次都有,但大约有95%的时间)。该问题也发生在其他计算机上,并且使用了最新的Chrome版本。

1 个答案:

答案 0 :(得分:0)

loadchildren synax:

{
  path: 'admin',
  loadChildren: 'app/admin/admin.module#AdminModule',
  canLoad: [AuthGuard]
},

在你的情况下应该是:

  const appRoutes: Routes = [   
      { path: 'user', 
        loadChildren: 'app/ROLE_USER/user.module#UserModule', 
       canLoad:[AuthResolver] 
      },  
      {
        path: 'anotherPath', 
        loadChildren: 'anotherChildrenModule', 
        canLoad:[AuthResolver] 
       }
    ];