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>
それは
異なるサービスを使用し、このサービスを両方のサービスインスタンスに注入してデータを共有することができます。 –
@GünterZöchbauerあなたは別のサービスの中にあるサービスを注入する方法を教えてください。私はこのコンストラクタ(@Inject(DateService)dateService){ } を試しましたが、動作していません –
@GünterZöchbauer私はそれを得ました。ありがとう!! –