My application has an architecture as follows:
Once the user log in, I navigate to the MainModule (lazy) where I register the services used in the MainModule's components. CarService caches the result of the webservice so, if the user logs out, I need this service to be destroyed. When the user logs out I navigate to the LoginModolue.
I thought that navigating to the LoginModule, the MainModule would have been destroyed (in fact I register it in the MainModule, not in the AppModule) but I noticed that if I log in again the old cache is still there. Is this normal? Shouldn't be destroyed the services provided in the MainModule when I navigate to the LoginModule?
You would expect that to happen, unfortunately because of the nature of lazy modules, this is not what happens, read here why not. Basically the lazy loaded module stays in the memory.
What you can do however is put the provider on the main component view:
@NgModule({
declarations: [
MainComponent
]
})
export class MainModule {}
@Component({
//...
providers: [ CarService ]
})
export class MainComponent {}
This will destroy the CarService
instance when the MainComponent
gets destroyed