如何以角度来销毁服务实例?

时间:2017-08-22 19:26:10

标签: 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']);
   }

LogComponent:

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

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

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

1 个答案:

答案 0 :(得分:1)

据我所知,你无法做你想要的事。我的建议是在LogService中添加一个函数,该函数将清除您想要在使用后删除的数据。例如:

export class CurrentUserService {
  productId: number | null;

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

当您想要破坏您的服务时,只需拨打电话即可。因为当您以这种方式提供服务时,您实际上无法销毁该服务。如果您以某种方式实际销毁AppModule级别的服务,则使用该服务的任何组件都将失败,包括您的LogComponent,因为它取决于该注入。

相关问题