为什么在angularjs服务中这个内部函数是未定义的?
.service('SliceService', function () {
var self = this;
var Slice = function(intervals, intervalSpan) {
self.activeSlice = [];
self.hasNext = true;
self.hasPrevious = false;
self.intervals = intervals;
self.intervalSpan = intervalSpan;
}
Slice.prototype.findIntervalIndex = function (time, slice) {
slice = slice || self.intervals;
return _.findIndex(slice, function (o) {
return o.time === time;
});
};
return Slice;
})
.controller('myController', ['SliceService', function(SliceService) {
SliceService([arr], 12);
SliceService.findINtervalIndex(time);
}])
在上面的示例中,当在控制器中使用它时,this.activeSlice会抛出错误TypeError: Cannot set property 'activeSlice' of undefined
。
-
谢谢大家!我已经更新了我的例子以更好地反映我正在尝试做的事情。上面我得到了TypeError: SliceService.findIntervalIndex is not a function
- 也许服务不适合我想做的事情?
答案 0 :(得分:2)
尝试保存"这个"的值在匿名范围内访问之前:
(function(){
'use strict';
angular.module('myServices').service('SliceService', function () {
var context = this;
var Slice = function(intervals, intervalSpan) {
context.activeSlice = [];
context.hasNext = true;
context.hasPrevious = false;
context.intervals = intervals;
context.intervalSpan = intervalSpan;
}
return Slice;
});
}());
使用Bind:
angular.module('myServices').service('SliceService', function () {
var Slice = function(intervals, intervalSpan) {
this.activeSlice = [];
this.hasNext = true;
this.hasPrevious = false;
this.intervals = intervals;
this.intervalSpan = intervalSpan;
}.bind(this);
return Slice;
});
注意:强> 使用javascript的箭头功能ES6确保 this 始终指向相同的上下文。所以你可以用箭头功能替换常规功能。然而,如果不进行转换,这并不是普遍支持的。
service('SliceService', ()=>{
// operations
}
答案 1 :(得分:0)
感谢@SeedyROM以及针对角度服务的一些额外谷歌搜索。这解决了我所有的问题...
angular.module('vpower.services').service('SliceService', function () {
this.activeSlice = [];
this.hasNext = true;
this.hasPrevious = false;
this.intervals = [];
this.intervalSpan = 12;
this.findIntervalIndex = function (time, slice) {
var curTime;
slice = slice || this.intervals;
return _.findIndex(slice, function (o) {
curTime = o.time._i || o.time;
return curTime === time;
});
};
我认为我并没有完全理解服务的运作方式。