Restangular promise then function 的作用域

Scope of Restangular promise then function

我试图了解我在 restangular 服务上调用的 then 函数的范围。我试图仅在 restangular 承诺解决时调用服务内的函数。

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
    };
});

您可以在 then 回调中使用缓存 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);