Search code examples
angularrxjsangular-routing

Angular 7: PreloadingStrategy extended method being called infinite time


I have a problem in preloading my modules. In start, I have just a setup module which was being pre-loaded. But when I changed the strategy for Security Module, my preLoading Strategy is not working as expected. It is being called infinitely.

Here is my code

const appRoutes: Routes = [
 {path: '', redirectTo: 'login', pathMatch: 'full', canActivate: [AuthGuard]
},

  {path: 'login', component: LoginComponent},
  {path: 'home', component: WelcomeComponent, children: [
  {path: 'security',loadChildren: './modules/security/security.module#SecurityModule', data:{preload: true }},
    {path: 'setup',loadChildren: './modules/setup/setup.module#SetupModule', data: { preload: false }}
    ]}

  ];

Here is my PreloadingStrategy implementation.

import { Injectable } from '@angular/core';
import { PreloadingStrategy, Route } from '@angular/router';
import { Observable, of } from 'rxjs';

@Injectable()
export class SelectivePreloadingStrategy implements PreloadingStrategy {
  preloadedModules: string[] = [];

  preload(route: Route, load: () => Observable<any>): Observable<any> {
        if (route.data && route.data['preload']) {
              this.preloadedModules.push(route.path);

          console.log('Preloaded: ' + route.path);

          return load();
    } else {
      return of(null);
    }
  }
}

Image is showing continuously (399+) called this strategy method.

enter image description here

EDIT:

Here is my security module code:

import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';
import { SysCommonModule } from '../common/sys.common.module';

@NgModule({
  declarations: [

  ],
    entryComponents: [

    ],

  imports: [

    /**** Angular ******/
    CommonModule,
    FormsModule,
    ReactiveFormsModule,

    /**** Third Party Controls ******/



    /**** Custom ******/
    SysCommonModule


  ],
  providers: []
})
export class SecurityModule {}

Solution

  • Add an empty routing module can stop the preload infinite loop. Don't know why. it just works.

    I guess the preload logic require module router configuration. If the router configuration missed, the framework would work as expected. I think it should be the bug or defect of the framework, it should be aware of that and report a warning or error message at least.

    @NgModule({
      declarations: [],
      imports: [
        CommonModule,
        RouterModule.forChild([]) // <= add an empty router configuration.
    
      ]
    })
    export class SecurityModule { }