【问题标题】:How store $http get response in variable accesible from outside $http function (Angularjs)?如何将 $http 获取响应存储在可从 $http 函数(Angularjs)外部访问的变量中?
【发布时间】:2016-05-16 11:40:41
【问题描述】:

我还在学习 Angular 和 javascript,我找到了堆栈 溢出真的很有帮助。实际上,这是我第一次在这里的其他问题和答案中找不到我的问题的解决方案。我尝试了很多解决方案,但没有什么对我有用。

简而言之:我想将来自 $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(用户单击“登录”按钮),然后我尝试使用响应来显示用户详细信息。但是在$scope.logIn()之外,$scope.userData又变成了一个空对象。

【问题讨论】:

  • 为什么要存储该响应?
  • 你能设置一个 plunkr 吗?这将有助于更快地找到解决方案。
  • 是“UserController”中的“consoleLog”方法吗?
  • 我想存储响应,以便我可以在站点上显示响应详细信息(如用户名),并在 $http 补丁等其他功能中使用响应详细信息 - 这样用户就不必再写用户名了
  • 'consoleLog() 是 'UserController' 中的方法

标签: javascript angularjs factory http-get


【解决方案1】:

我假设你在 onclick 中调用登录方法。试试这个:;

$scope.logIn = function() {  // function runs on click

    getUserFactory.getUserData(user.email, user.password).then(function(response){

    $scope.userData = response.objects[0];  

    });            

};

【讨论】:

    猜你喜欢
    • 2021-07-18
    • 1970-01-01
    • 2016-02-28
    • 1970-01-01
    • 2016-04-05
    • 1970-01-01
    • 2015-11-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多