如何在角度工厂中存储来自http服务的数据

时间:2014-12-09 18:24:00

标签: angularjs

我想使用服务全局存储/api/login.json中的值,但我认为我有某种时序问题。控制器中的console.log语句告诉我scope.login对象未定义。

我错过了什么?

谢谢!

工厂服务:

myApp.factory('LoginFactory', ['$http', function($http){

    this.data;
    $http.get('/api/login.json').success(function(data) {
        this.data = data;
    });

    return {
        getData : function(){
        return this.data;
    }
  }
}]);

控制器:

myApp.controller('AccountsCtrl', ['$scope', 'Accounts', 'LoginFactory', function($scope, Accounts, LoginFactory){
  $scope.login = LoginFactory.getData();
  console.log('$scope.login: %o', $scope.login);    
  $scope.accounts = Accounts.index();

}]);

3 个答案:

答案 0 :(得分:9)

您应该避免在此上下文中使用this关键字。更好的方法是声明一个新变量。

myApp.factory('LoginFactory', ['$http', function ($http) {
    var data;
    $http.get('/api/login.json').success(function (d) {
        data = d;
    });
    return {
        getData: function () {
            return data;
        }
    };
}]);

你仍然会遇到种族问题,所以我也会推荐诺言链接

myApp.factory('LoginFactory', ['$http', function ($http) {
    var promise = $http.get('/api/login.json');
    return {
        getData: function (callback) {
            promise.success(callback);
        }
    };
}]);

甚至是条件获取

myApp.factory('LoginFactory', ['$http', function ($http) {
    var data;
    return {
        getData: function (callback) {
            if(data) {
                callback(data);
            } else {
                $http.get('/api/login.json').success(function(d) {
                    callback(data = d);
                });
            }
        }
    };
}]);

最后两种方法要求您通过

重写控制器
myApp.controller('AccountsCtrl', ['$scope', 'Accounts', 'LoginFactory', function($scope, Accounts, LoginFactory){
  LoginFactory.getData(function(data) {
      $scope.login = data;
      console.log('$scope.login: %o', $scope.login);    
      $scope.accounts = Accounts.index(); //this might have to go here idk
  });
}]);

答案 1 :(得分:3)

扩展@LoganMurphy答案。使用promise并仍然添加回调根本不可取。编写服务的更好方法可能是

myApp.factory('LoginFactory', ['$http', function ($http, $q) {
    var data;
    return {
        getData: function () {
            if(data) {
                return $q.when(data);
            } else {
                return $http.get('/api/login.json').then(function(response){
                    data = response;
                    return data;
                });
            }
        }
    };
}]);

答案 2 :(得分:0)

this关键字存在问题,您也无法正确处理http.get中的承诺

我会这样写:

myApp.factory('LoginFactory', ['$http', function($http){

    return {
        getData : function(){
        return $http.get('/api/login.json');
    }
  }
}]);


myApp.controller('AccountsCtrl', ['$scope', 'Accounts', 'LoginFactory', function($scope, Accounts, LoginFactory){
  $scope.login = LoginFactory.getData().success(function(data){
     console.log(data);
     console.log('$scope.login: %o', $scope.login); 
  });

}]);
相关问题