【发布时间】:2017-10-19 08:01:55
【问题描述】:
是否可以在同一服务的 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
}
我需要在我的应用程序的多个页面上使用相同的日期。但是模式我想让它特定于使用此服务的组件。
<some-component [(date)]="dateService.selectedDate" [(mode)]="YEAR"></some-component>
当我点击这个组件中的 nextDate 按钮时,它应该转到明年
<someother-component [(date)]="dateService.selectedDate" [(mode)]="DAY"></someother-component>
当我从该组件中单击 nextDate 时,它应该转到第二天
【问题讨论】:
-
您可以使用不同的服务并将此服务注入两个服务实例以共享数据。
-
@GünterZöchbauer 请告诉我如何将一项服务注入另一项服务。我试过这个构造函数(@Inject(DateService) dateService) { } 但它不工作
-
@GünterZöchbauer 我明白了。谢谢!!
标签: angular typescript data-binding angular-services data-sharing