I have an Angular 9 app, I have noticed that my service gets reinitialized/reinstantiated everytime I navigate from a route to another. After a long debug and trials, I decided to log in the constructor of AppModule and noticed that it gets recalled for every route. NB: I inject my service using providedIn: 'root'. I have as well tried to declare the service in AppModule providers attribute instead of using providedIn, but still same result.
Any ideas?
Here is my AppModule:
@NgModule({
declarations: [
AppComponent,
...
],
imports: [
BrowserModule,
StoreModule.forRoot({user : userReducer}),
AppRoutingModule,
BrowserAnimationsModule,
FormsModule,
AngularFireModule.initializeApp(environment.firebase),
AngularFirestoreModule,
AngularFireStorageModule,
ReactiveFormsModule,
MatAutocompleteModule,
NgbModule.forRoot(),
FontAwesomeModule,
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule {
constructor(){
console.log('MODULE INIT');
}
}
Here is my routing module:
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule { }
The behavior you described makes me think your app is reloading a fresh state of itself each time you navigate. This can happen when:
href
attribute).In any case your code seems right and you seem to have taken in consideration the consequences of using a singleton service so it is likely for the issue to not come from a service providing trouble.