以角度2在两个不同组件之间传递数据

时间:2016-09-04 13:22:11

标签: angular components

我有两个不同的单独组件,我希望在两者之间共享任何数据意味着任何变量数据在一个组件中更新,然后它应该在其他组件的视图中自动更新。 需要帮助。

1 个答案:

答案 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();