服务生命周期(销毁服务)

use*_*528 3 angular-module angular angular-router

我的应用程序的架构如下: 在此处输入图片说明

用户登录后,我导航到MainModule(懒惰),在那里注册MainModule组件中使用的服务。 CarService缓存 Web 服务的结果,因此,如果用户注销,我需要销毁此服务。当用户注销时,我导航到LoginModolue

我认为导航到LoginModuleMainModule会被破坏(实际上我在MainModule 中注册它,而不是在 AppModule 中)但我注意到如果我再次登录,旧的缓存仍然存在。这是正常的吗?当我导航到LoginModule时,不应该破坏MainModule 中提供的服务吗?

Pie*_*Duc 5

您会期望这种情况发生,不幸的是,由于惰性模块的性质,这不会发生,请在此处阅读为什么不这样做。基本上懒加载模块留在内存中。

但是,您可以做的是将提供程序放在主组件视图上:

@NgModule({
  declarations: [
     MainComponent
  ]
})
export class MainModule {}

@Component({
  //...
  providers: [ CarService ]
})
export class MainComponent {}
Run Code Online (Sandbox Code Playgroud)

这将在CarService实例MainComponent被销毁时销毁实例