我想在我的过滤器中使用$http
服务。现在我收到以下错误
angular.js:12477 TypeError: Cannot read property 'get' of undefined
at factory (next-schedule-occurrence.filter.js:32)
...
如何正确注入$http
?
HTML模板:
<p>Next execution: {{watcher._source.trigger.schedule.later | nextScheduleOccurrence}}</p>
过滤代码:
/* 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);
更新
如果我使用过滤器的函数而不是类,我会得到相同的错误。
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);
答案 0 :(得分:1)
我认为你的工厂方法应该返回一个像这样的函数
static factory($http) {
return function(schedule) {
const filter = new NextScheduleOccurrence(schedule);
return $http.get('../api/sentinl/config').then((config) => {
return filter.next(config);
});
}
}