AngularJs服务从then()上下文访问服务上下文

时间:2015-09-15 16:54:45

标签: angularjs

我可能犯了初学者的错误。我正试图弄清楚如何在承诺的this部分内访问服务的then()上下文中的函数或变量。

以下是一些示例代码:

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

}]);

如何联系saveLoginInfo功能?

1 个答案:

答案 0 :(得分:3)

当您在JS中输入函数时,上下文将更改为当前函数。您可以将this分配给可验证的人来解决范围。

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

}]);