【问题标题】:Angular2 share data between 2 instances of same serviceAngular2 在同一服务的 2 个实例之间共享数据
【发布时间】: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


【解决方案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() 时,请确保您将模式作为参数传递并设置好了。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-05-18
    • 2017-07-22
    • 1970-01-01
    • 1970-01-01
    • 2021-09-16
    相关资源
    最近更新 更多