Hey guys, I’m experiencing a strange issue.
I’m aware that ngOnInit() should only run once, when the component is loaded, and after that only ionViewDidEnter() signals, that the user has navigated to the given component. In spite of this, ngOnInit() gets called (usually?) when a user navigates to a component, regardless if he has been there before.
I have lazy loading configured in the application.
Here is part of the app-routing.module.ts
{
path: 'home',
canActivate: [AuthGuard],
loadChildren: './home/home.module#HomePageModule',
resolve: { homeData: HomeResolver },
data: {
frame: true,
},
},
{
path: 'news',
canActivate: [AuthGuard],
loadChildren: './news/news.module#NewsPageModule',
data: {
frame: true,
},
},
{
path: 'client-status',
canActivate: [AuthGuard],
loadChildren: './client-status/client-status.module#ClientStatusPageModule',
resolve: { clientStatusData: ClientStatusResolver },
data: {
frame: true,
},
},
Here is client status page module for example:
const routes: Routes = [
{
path: '',
component: ClientStatusPage
}
];
@NgModule({
imports: [
IonicModule,
CommonModule,
AppCoreModule,
FormsModule,
PipesModule,
InlineSVGModule.forRoot(),
RouterModule.forChild(routes),
],
declarations: [ClientStatusPage]
})
export class ClientStatusPageModule {}
Everything is similar to what we can find in tutorials.
The difference is in maybe in the html structure, and the components providing it.
app-component.html:
<ion-app>
<app-frame *ngIf="frame; else noframe">
<ng-container *ngTemplateOutlet="noframe"></ng-container>
</app-frame>
<ng-template #noframe>
<ion-router-outlet></ion-router-outlet>
</ng-template>
</ion-app>
The frame variable comes from the data provided in the routing
data: {
frame: true,
},
We use this component to render a header and a footer in the application, frame.component.html:
<ion-header>
<app-header></app-header>
</ion-header>
<div>
<ng-content></ng-content>
</div>
<ion-footer>
<app-menu></app-menu>
</ion-footer>
In the footer there is a menu with some anchor tags, pointing to the urls defined in app-routing.module.ts.
For example:
<a routerLink="/home" routerLinkActive="active">
Home
</a>
So the behaviour I’m experiencing, is that from the Home module, if I click on any anchor tag (for example Settings), and load up a module, the settings.page.ts ngOnInit gets called. If I navigate back to Home, the home.page.ts ngOnInit doesn’t get called a 2nd time. But if I navigate to Settings again, the settings.page.ts ngOnInit of gets called again.
Sometimes all of the components trigger ngOnInit upon navigation, sometimes a given component’s ngOnInit gets triggered only if I navigate there from 1-2 particular component, but doesn’t get triggered if I navigate there from a different one.
Sorry for the cloudy explanation, but I’m totally clueless why this happens, hope someone can point me in the right direciton.