首页 > 解决方案 > 角度自定义预加载未在多模块应用程序中调用

问题描述

问题:我已经实现了客户预加载功能。登录后,应用程序LayoutModule将被加载,但不会调用 Custome Preloading 函数。我以不同的方式尝试过,但花了更多时间。任何人都请帮助我。

在我的应用程序中,我使用了两种类型的核心模块。

登录后,应用程序首先会加载 LayoutModule。LayoutModule 包含不同类型的子模块。首先将加载仪表板模块。另一个模块,如 CustomerModule 未预加载。

这是我的自定义预加载策略功能

@Injectable({
  providedIn: 'root'
})
export class CustomPreloadingStrategy implements PreloadingStrategy {
  preload(route: Route, loadMe: () => Observable<any>): Observable<any> {
    if (route.data && route.data['preload']) {
        var delay: number = route.data['delay'];
        console.log('preload called on ' + route.path + ' delay is ' + delay);
        return timer(delay).pipe(
            flatMap(_ => {
                console.log("Loading now " + route.path);
                return loadMe();
            })
        )
    } else {
        console.log('no preload for the path ' + route.path);
        return of(null);
    }
  }
}

这是我的 AuthenticationRoutingModule。

const routes: Routes = [
{
    path: '',
    component: AuthenticationComponent,
    children: [
        {
            path: 'login',
            loadChildren: () => import('./login/login.module').then(t => t.LoginModule),
            data: { preload: true, delay: 5000 }
        },
        {
            path: '',
            pathMatch: 'full',
            redirectTo: 'login'
        }
    ]
}
];

@NgModule({
imports: [
    RouterModule.forChild(routes)
],
exports: [
    RouterModule
],
declarations: [],
providers: []
})

export class AuthenticationRoutingModule {
constructor() {
    console.log("Authentication Routing..");
}
}

这是我的 LayoutRoutingModule

const routes: Routes = [
{
    path: '',
    component: LayoutComponent,
    children: [
        {
            path: 'dashboard',
            loadChildren: () => import('./dashboard/dashboard.module').then(t => t.DashboardModule),
            data: { preload: true, delay: 5000 },
            canLoad: [AuthGuard],
        },
        {
            path: 'customer',
            loadChildren: () => import('./customers/customer.module').then(t => t.CustomerModule),
            data: { preload: true, delay: 10000 },
            canLoad: [AuthGuard],
        },
    ]
}
];

@NgModule({
imports: [
    RouterModule.forChild(routes)
],
exports: [
    RouterModule
],
declarations: [],
providers: []
})

export class LayoutRouting {
constructor() {
    console.log("Layout Routing..");
}
}

这是我的主要 AppModule。在模块中,我已经导入了AuthenticationLayout模块。

@NgModule({
  declarations: [
  AppComponent
  ],
  imports: [
   BrowserModule,
   AppRoutingModule,    
   AuthenticationModule,   
   LayoutModule,
   PageNotFoundModule,
  ],
  providers: [
   CustomPreloadingStrategy,
   TestingService
  ],
  bootstrap: [AppComponent]
    })

export class AppModule { }

标签: angular

解决方案


我创建了一个简短的视频解释如何创建自定义预加载策略 - https://www.youtube.com/watch?v=tDQc3CCvKfc 希望这将有助于解决您的问题

这是代码 - https://github.com/stevermeister/AngularPro-Screencast/tree/master/code/Season4-Router-Features/preloading


推荐阅读