Scope of Restangular promise then function

Issue

Im trying to understand the scope of the then function that I call on my restangular service. Im trying to call a function inside a service only when a restangular promise resolves.

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

Solution

You can use cached this inside the then callback.

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

You can also use the function reference as

rest.getSomething().then(this.doSomethingElse);

Answered By – Tushar

Answer Checked By – Marilyn (AngularFixing Volunteer)

Leave a Reply

Your email address will not be published.