我试图理解我在restangular服务上调用的then函数的范围。我试图只在restangular promise解决时才调用服务中的函数。
angular.module('app').service('test', function(rest) {
this.doSomething = function() {
console.log(this); // this logs the current object im in
rest.getSomething().then(function(data) {
console.log(this); // this logs the window object
this.doSomethingElse(); // this is what I want to call but is is not in scope and I cant seem to get my head around as to why.
}
};
this.doSomethingElse = function() {
// Do something else
};
});
答案 0 :(得分:1)
您可以在当时的回调中使用缓存的this
。
angular.module('app').service('test', function (rest) {
this.doSomething = function () {
var self = this; // Cache the current context
rest.getSomething().then(function (data) {
self.doSomethingElse(); // Use cached context
});
};
this.doSomethingElse = function () {
// Do something else
};
});
您也可以将函数引用用作
rest.getSomething().then(this.doSomethingElse);