Search code examples
javascriptangularjsangularjs-filter

Inserting service in ES6 class filter


I want to use $http service inside my filter. Now I get the following error

angular.js:12477 TypeError: Cannot read property 'get' of undefined
    at factory (next-schedule-occurrence.filter.js:32)
...

How can I inject $http correctly?

HTML Template:

<p>Next execution: {{watcher._source.trigger.schedule.later | nextScheduleOccurrence}}</p>

Filter code:

/* global angular */
import moment from 'moment';
import later from 'later';

/*
* Get the next occurence of from the 'later' lib text schedule
*/
class NextScheduleOccurrence {

  /*
  * @param {string} schedule in English for the 'later' text parser
  */
  constructor(schedule) {
    this.schedule = schedule;
  }

  /*
  * @return {string} the future occurrence for the schedule
  */
  next(config) {
    if (config.es.watcher.schedule_timezone === 'local') {
      later.date.localTime();
    }
    return moment(later.schedule(later.parse.text(this.schedule)).next()).format('D/M/YYYY H:m:s');
  }

  /*
  * @param {string} schedule in English for the 'later' text parser
  */
  static factory(schedule, $http) {
    const filter = new NextScheduleOccurrence(schedule);
    return $http.get('../api/sentinl/config').then((config) => {
      return filter.next(config);
    });
  }
}

NextScheduleOccurrence.factory.$inject = ['schedule', '$http'];
export default angular.module('nextScheduleOccurrence', [])
.filter('nextScheduleOccurrence', () => NextScheduleOccurrence.factory);

UPDATE

I get the same error if I use a function for the filter instead of the class.

const NextScheduleOccurrence = function (schedule, $http) {
  return $http.get('../api/config').then((config) => {
    if (config.es.watcher.schedule_timezone === 'local') {
      later.date.localTime();
    }   
    return moment(later.schedule(later.parse.text(schedule)).next()).format('D/M/YYYY H:m:s');
  }); 
};

NextScheduleOccurrence.$inject = ['schedule', '$http'];
export default angular.module('nextScheduleOccurrence', []).filter('nextScheduleOccurrence', () => NextScheduleOccurrence);

Solution

  • I think your factory method should return a function like this

    static factory($http) {
      return function(schedule) {
        const filter = new NextScheduleOccurrence(schedule);
        return $http.get('../api/sentinl/config').then((config) => {
          return filter.next(config);
        });
      }
    }