[英]Scope of Restangular promise then function
我試圖理解我在restangular服務上調用的then函數的范圍。 我試圖僅在重新約定約定解決時才在服務內調用函數。
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
};
});
您可以使用緩存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);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.