Angular2在同一服务的2个实例之间共享数据

时间:2017-05-19 09:05:34

标签: angular typescript data-binding angular-services data-sharing

是否可以在同一服务的两个实例之间共享数据?

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时,它应该转到第二天

1 个答案:

答案 0 :(得分: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.
}

基本上,每当您从公共nextDate()拨打DateService时,请确保将该模式作为参数传递并设置。