我有两个不同的单独组件,我希望在两者之间共享任何数据意味着任何变量数据在一个组件中更新,然后它应该在其他组件的视图中自动更新。 需要帮助。
答案 0 :(得分:1)
创建一个可注入服务,用于保存组件之间共享所需的数据。在此服务上创建事件侦听器事件发射器,如下所示:
@Injectable()
export class YourGlobalService {
public doComponentDataUpdate = new EventEmitter();
public sharedData: any;
constructor() {}
}

现在,在您需要获取共享数据的任何组件中,执行以下操作:
import { Component, ViewEncapsulation } from "@angular/core";
import { YourGlobalService } from "./path/your-global.service";
@Component({
selector: "some-component",
moduleId: module.id,
providers: [],
templateUrl: "./some-component.html",
encapsulation: ViewEncapsulation.None,
})
export class SomeComponent {
localData: any;
doComponentDataUpdate: any;
constructor(yourGlobalService: YourGlobalService) {
this.doComponentDataUpdate = yourGlobalService.doComponentDataUpdate.subscribe(() => {
// when this is fired, your component knows to check for new data
this.localData = yourGlobalService.sharedData;
});
}
ngOnDestroy() {
// don't forget to unsubscribe!
this.doComponentDataUpdate.unsubscribe();
}
}

yourGlobalService.doComponentDataUpdate.emit();