$ http.get中的angular JS $ rootScope undefined

时间:2015-11-11 16:54:43

标签: angularjs undefined

我想从$ http.get中检索数据并将其放入$ rootScope:

.RUN

app.run(function ($rootScope, $q, $http, $timeout, stateRules) {

    stateRules
    .then(function (data) {
        $rootScope.user = data;
        console.log(data);
    });   
});

。服务

 app.service('stateRules', ['$http','$q', function($http, $q) {
    var userUrl= 'api/user/';
    var userService = {};
    var deferred = $q.defer();
    $http.get(userUrl+ "getUserName", { cache: true }).success(function (data) {
        deferred.resolve(data);
    });
    return deferred.promise;
});

.controller

app.controller('userCtrl', ['$scope', function ( $scope) {
        console.log($scope.user);

}]);

但我的控制器中$ scope.user的值未定义。知道怎么解决吗? 感谢

1 个答案:

答案 0 :(得分:0)

$ rootScope应该注入服务中。像这样。

.service('ServiceGetSVC', ['$http','$rootScope','$q',function ($http,$rootScope,$q) {....}

或者如果您尝试在方法get之后使用$ rootScope.user。由于方法异步,因此未定义。应该使用延期。

在申请中

ServiceGetSVC.then(data){
  $rootScope.user = data;
}

service 
  .service('stateRules', ['$http','$q' function($http, $q) {
    var deferred = $q.defer();
    $http.get(communUrl + "getUserName", { cache: true }).success(function (data) {
        deferred.resolve(data);
    });
    return deferred.promise;
  }])