my target is a bit bigger but for now i just want to execute a function before the child routes are loaded, i have this:
features.module.ts
export function initializeApp(appInitService: AppInitService) {// esta funcion es la que quiero ejecutar
return (): Promise<any> => {
console.log("este si lo esta llamando");
return appInitService.Init();
}
}
const routes: Routes = [...];
@NgModule({
declarations: [...],
imports: [...,
RouterModule.forChild(routes)// aquí cargo mis routers child
],
schemas:[NO_ERRORS_SCHEMA],
providers: [
{
provide: APP_INITIALIZER,// este es el tipo de provider
useFactory: initializeApp,// aquí esta la promesa que quiero ejecutar
multi: true,
deps: [AppInitService]
}
]
})
export class FeaturesModule { }
Here I have the function that will be executed when the module is called, and app.module.ts
that calls me FeaturesModule
by lazy loading:
app.module.ts
const routes: Routes = [
{
path: '', component: HomeComponent, canActivate: [AuthGuard],
loadChildren: () => import('./features/features.module').then(m => m.FeaturesModule)
},
{
path: 'login',
component: LoginComponent
}
];
@NgModule({
declarations: [
AppComponent,
HomeComponent,
LoginComponent
],
imports: [...,
RouterModule.forRoot(routes)
],
schemas:[NO_ERRORS_SCHEMA],
bootstrap: [AppComponent]
})
export class AppModule { }
but it is not working for me, it should tell me "this is calling it" in the browser console, I am guided by this answer stackoverflow.com
The problem is that you are using
APP_INITIALIZER
in a module loaded bylazy-loading
, which is impossible for angular to load your service. This is because, as its name says, it is executed once the application is initialized and the application is only executed once before thebootstrap
.Your module is not loading until after initialization or when you request it by lazy-loading. The ideal is that you
APP_INITIALIZER
are in yourapp.module.ts
.