为什么每次创建组件后我都会引用以前的数据?

Why each time after creating component I have reference to previous data?

我有组件通过事件消息从服务获取数据:

this.objectDetailsSubscription = this.eventService.subscribe(
      EventsChannels.OBJECT_DETAILS,
      semantic => {
        this.layer = this.layerSemanticService.getObjectSemantic(semantic);
      }
    );

服务地点:

@Injectable({
  providedIn: "root"
})
export class LayersSemanticService {
  getObjectSemantic(semantic: LayerItemGeneric): ObjectInformationCustom {
    this.semantic = semantic;
    this.configuration = this.getConfigurationSemantic(semantic.layerIdCommon);

    return {
      buttons: this.getButtons(this.configuration),
    }

  }

    getButtons(configuration: LayerSemanticConfig) {
    configuration.tools = configuration.tools || [];
    configuration.tools.push(EButtonTypes.Pin);
    return configuration.tools; 
  }
}

在子组件中,我将按钮作为 Input():

  *ngFor="let btn of buttons"

我尝试重置变量:

 ngOnInit() {
    this.layer = <ObjectInformationCustom>{};
}

无效果

默认情况下,服务是单例的(当用 @Injectable({ providedIn: 'root' }) 装饰时,就像你的一样)。

这意味着在应用程序的整个生命周期中,只有一个实例驻留在内存中。因此,服务中存在的状态对于注入服务的所有组件都是相同的,直到该状态发生变化。

如果状态不应存在于组件的生命周期之外,则将该状态存储在组件中。如果需要在服务中存储和更新,那就在服务中更新。

可以通过在 @Component() 装饰器中将它们设置为 providers 来配置组件级服务。不过,这种方法需要谨慎使用,因为它可能会造成混淆。