angular - 如何在 Angular 中销毁服务实例?

标签 angular

在我的 Angular 应用程序中,我需要在一个组件与另一个组件之间共享一个服务实例,然后销毁该服务实例,该怎么做?

       AppModule
     /          \
 Module1        Module2
   /               \
ProductComponent    LogComponent              ? LogService

ProductComponent:

   constructor(private _logService: LogService) { }

   viewLog() {
      this._logService.productId = this.product.id;
      this._router.navigate(['/app/administration/logs']);
   }

日志组件:

  constructor(private _logService: LogService, private _adminService: AdminService) {

       this._adminService.getLogs(_logService.productId).subscribe(.....);
  }

我将 LogService 放在 AppModule 上以创建单例。它工作正常,但我不想在用户离开 LogComponent 后保留此 LogService 实例。我需要毁掉它。我怎样才能做到这一点?

最佳答案

据我所知,您无法执行您所要求的操作。我的建议是在 LogService 中包含一个函数,该函数将清除您想要在使用后删除的数据。例如:

export class CurrentUserService {
  productId: number | null;

  clearProductId() {
    this.productId = null;
  }
}

当您想要“销毁您的服务”时,只需调用它即可,因为当您以这种方式提供服务时,您实际上无法销毁服务。如果您以某种方式实际销毁 AppModule 级别的服务,则使用该服务的任何组件都将失败,包括您的 LogComponent,因为它依赖于该注入(inject)。

关于angular - 如何在 Angular 中销毁服务实例?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45825488/

相关文章:

forms - 即使设置为原始值,angular2 formcontrol 仍然很脏

angular - 如何在 Angular 2 中获取子组件的大小?

javascript - 将多个参数传递给 Angular 2 组件

angular - 如何重置 ngrx/store 的所有状态?

javascript - Angular 错误: Webpack has been initialised using a configuration object that does not match the API schem

Angular2提交表单值

angular - 如何防止从 PrimeNG 拖动 p-dialog 到屏幕外

javascript - 我们如何在没有直接 @Output 的情况下检测 Angular2 中是否运行了更改检测?

javascript - 标准 "Match URL"的预期匹配请求 - 未找到 - Angular2+

angular - 缓冲 Angular 服务 HttpClient 请求