0

I'm probably making a beginners mistake. I'm trying to figure out how to access a function or variable in the this context of a service, while within the then() portion of a promise.

Here's some example code:

ndtApp.service("userService", ['$http',
function($http){

    this.saveLoginInfo = function(data){
        //do some stuff here.
    }

    this.login = function(){
        //Login
        $http.get('http://example.com/userlogin').then(
            function(data){
                this.saveLoginInfo(data);
                //This won't work because 'this' from here is 'window' rather than the service.
            },
            function(data){
                //error handling
            });
    }

}]);

How do I reach the saveLoginInfo function?

2

1 Answer 1

3

When you enter a function in JS the context changes to the current function. You can assign this to a veriable to resolve the scope.

ndtApp.service("userService", ['$http',
function($http){
var self = this;
self.saveLoginInfo = function(data){
    //do some stuff here.
}

self.login = function(){
    //Login
    $http.get('http://example.com/userlogin').then(
        function(data){
            self.saveLoginInfo(data);
            //This won't work because 'this' from here is 'window' rather than the service.
        },
        function(data){
            //error handling
        });
}

}]);
Sign up to request clarification or add additional context in comments.

3 Comments

This did definitely work. Follow up question: Is the self now defined in window? Is that not a problem / something messy we should avoid?
@Coo self is defined in the context of the service. It will be available to any function you define within the service. I recommend reading the style guide sbat linked. It's a great resource
Thanks for that! I did read the style guide which has led me to start using IIFE's which solved my pollution problem.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.