Search code examples
angularjsmeteorcomponentsangular-meteor

How to allow a function in a component to access factory imported in constructor?


I have been trying to share data between components and followed advice from here to make a store.

It all works great from within my components constructor but I can't figure out how to give the functions similar access.

class Home {
  constructor($scope, $reactive, Store) {
    'ngInject';

    $reactive(this).attach($scope);

    this.selectedDate = Store.get().selectedDate;
}

That all works, but accessing the Store here doesn't work:

nextDay(){
    'ngInject';
    Store.set({selectedDate: moment(this.selectedDate).add(1, 'd').format('YYYY-MM-DD')});
    console.log('nextDay');
}

I have tried attaching Store to $reactive, I have tried this.Store and passing Store as an agrument to nextDay() but can't figure it out. Any help would be greatly appreciated.

Thanks


Solution

  • You should assign the services(injected things) on the Class

    for example if you wanna use Store assign this.Store = Store and then you can use it from all the methods in the class as this.Store

      class Home {
          constructor($scope, $reactive, Store) {
            'ngInject';
            this.Store = Store;
            this.$reactive = $reactive;
            this.$scope = $scope;
            this.$reactive(this).attach($scope);
    
            this.selectedDate = this.Store.get().selectedDate;
          }
    
          nextDay(){
            this.Store.set({selectedDate: moment(this.selectedDate).add(1, 'd').format('YYYY-MM-DD')});
            console.log('nextDay');
    
          }
      }