存储$http如何从$http函数(Angularjs)外部获取可访问变量中的响应

How store $http get response in variable accesible from outside $http function (Angularjs)?

本文关键字:http 访问 获取 变量 响应 外部 Angularjs 函数 存储      更新时间:2023-09-26

我仍在学习angular和javascript,我发现了stack溢出真的很有帮助。事实上,这是我第一次在其他问题中找不到解决问题的方法;答案在这里。我尝试了很多解决方案,但都不起作用。

简而言之:我想把$http-get(用户数据)的响应保存在变量中,这样我就可以在这个控制器的其他函数中使用它。

我的工厂与$http获取功能:

    app.factory('getUserFactory', ['$http', function($http){ 
    return {
        getUserData : function(email, password) {
            return $http.get('https://xxxxxxx.xxx.xx/api/v1/user/', {
            headers: {
            "Authorization": 'Basic '+ window.btoa(email +':'+password)
            }                
            });
        }            
    };
}]);

我的控制器功能:

 app.controller('UserController', ['$scope','$http', 'getUserFactory', function($scope, $http, getUserFactory) {
 var user= {};    //Used to bind input fields from html file
 $scope.user= user;  
 $scope.userData = {}; // <-- HERE I WANT TO STORE RESPONSE
 $scope.logIn = function() {  // function runs on click
        getUserFactory.getUserData(user.email, user.password).success(function(response){
        $scope.userData = response.objects[0];                                  
        });            
 };

我用简单的点击功能来测试它是否有效:

 $scope.consoleLog = function () {
        console.log($scope.userData);
    }; 

我认为我的问题与javascript的异步有关,但我总是先调用$http-get(用户单击"登录"按钮),然后尝试使用response来显示用户详细信息。但在$scope.logIn()之外,$scope.userData又变成了一个空对象。

我假设您正在onclick中调用登录方法。只需尝试以下操作:;

$scope.logIn = function() {  // function runs on click
    getUserFactory.getUserData(user.email, user.password).then(function(response){
    $scope.userData = response.objects[0];  
    });            

};