控制器AngularJS中未定义服务数据

时间:2017-09-11 11:27:18

标签: angularjs

我正在尝试访问服务,然后将响应返回给Controller以获取共享数据。这是我的服务,它返回电话列表:

app.service('DataService', ['$http', function($http){
    this.getData = function(){
        var promise = $http.get('js/products.json').then(function(response){
            return response.data;
        });
        return promise;
    }
}]);

在控制器中:

app.directive('phoneList',[function(){
    return {
        restrict: 'E',
        templateUrl: 'phone-list.html',
        controller: ['$http', '$scope', 'DataService', function($http, $scope, DataService){
            DataService.getData()
            .then(function(response){
                $scope.products = response;
            });
            console.log($scope.products)
        }],
        controllerAs: 'homeCtrl'
    };
}]);

但是当我在Console中记录$ scope.products时,它只是打印undefined。任何线索都会受到赞赏。

2 个答案:

答案 0 :(得分:1)

$http返回一个承诺。因此,在您的服务中,您必须将$http电话作为承诺返回。

将您的服务替换为:

app.service('DataService', ['$http', function($http){
    this.getData = function(){

        // Create a var. This will hold the angular promise which you have to return later on
        var promise = $http.get('js/products.json').then(function(response){

            // Return the data which can be called inside the .then(DATA)
            return response.data;
        });

        // Return the promise
        return promise;
    }
}]);

然后将控制器编辑为:

app.directive('phoneList',[function(){
    return {
        restrict: 'E',
        templateUrl: 'phone-list.html',
        controller: ['$http', '$scope', 'DataService', function($http, $scope, DataService){

            // Handle the promise
            DataService.getData().then( function(response) {
                $scope.products = response;
                console.log($scope.products)
            });
        }],
        controllerAs: 'homeCtrl'
    };
}]);

答案 1 :(得分:0)

尝试从url

获取对象后返回该对象
app.service('DataService', ['$http', function($http){
    this.getData = function(){
        var data = $http.get('js/products.json').then(function(response){
            return response.data;
        });
       if(data)
        return data;
    }}]);