Restangular承诺的范围然后功能

时间:2015-09-22 07:55:52

标签: javascript angularjs restangular

我试图理解我在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
    };
});

1 个答案:

答案 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);