在我的 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/