1

同じサービスの2つのインスタンス間でデータを共有できますか?私は自分のアプリケーションで複数のページで使用する必要がAngular2は同じサービスの2つのインスタンス間でデータを共有します

DateService.ts

private _selectedDate: Date = new Date(); 

private _mode = 'YEAR'; //can be DAY,WEEK,MONTH also 

set selectedDate(newSelectedDate) { 
     this._selectedDate = newSelectedDate; 
    } 

    get selectedDate() { 
     return this._selectedDate; 
    } 

set mode(newMode) { 
     this._mode = newMode; 
    } 

    get mode() { 
     return this._mode; 
    } 

nextDate() { 
     //based on mode this will change the date 
    // if the mode is year then this gives next year 
    // if the mode is month then next month etc... and updates the date 
    } 

同じ日付。しかし、私はこのサービスを使用するコンポーネントに固有のものにしたいと思います。私はこのコンポーネントからnextDate]ボタンをクリックしたときに、私はこのコンポーネントからnextDateをクリックしたとき、それは次の日に行くべき

<someother-component [(date)]="dateService.selectedDate" [(mode)]="DAY"></someother-component> 

<some-component [(date)]="dateService.selectedDate" [(mode)]="YEAR"></some-component> 

それは

+2

異なるサービスを使用し、このサービスを両方のサービスインスタンスに注入してデータを共有することができます。 –

+0

@GünterZöchbauerあなたは別のサービスの中にあるサービスを注入する方法を教えてください。私はこのコンストラクタ(@Inject(DateService)dateService){ } を試しましたが、動作していません –

+0

@GünterZöchbauer私はそれを得ました。ありがとう!! –

答えて

1

私はモードを渡す来年に行くべきパラメータとして使用します。 Component1

private mode = 'YEAR'; 

nextDate = this.dateService.nextDate(this.mode); 

Component2において:

private mode = 'DAY'; 

nextDate = this.dateService.nextDate(this.mode); 
DateService

において:

nextDate(mode) { 
    // do stuff with the mode. mode will be different depending who calls this function. 
    // If Component1 calls, mode will be YEAR. If Component2 calls, mode will be DAY. 
} 

基本的には、DateServiceからnextDate()を呼び出すたびに、モードをパラメータとして渡していることを確認してください。

関連する問題