2016-09-04 17 views

答えて

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

関連する問題