2017-02-01 30 views
0

我使用以下代码。我正在阅读的json文件名是“hassan.json”。如果我通过$ http在控制器中读取此文件,一切正常。但我想使用我从文件中读取的数据,一次又一次地在不同的控制器中,所以我为此做了一个服务。但服务时,当我通过$ http.get()从该json文件读取数据,并在我调用控制器和console.log(数据)时,它返回我这在控制台“e {$ $ state:object}“。

这是控制器

app.controller('showdata', function($scope, service){ 
    $scope.mydata = service.getData().then(function(user){ 
     $scope.mydata = (user.data); 
     console.log(($scope.mydata)); 
    }); 

}); 

服务我使用:

app.service('service', function($http, $q){ 
    var outData; 
    this.getData = function() { 
    if (this.outData === undefined) { 
    var deferred = $q.defer(); 
    $http.get('jsons/hassan.json') 
     .then(function(data){ 
      this.outData = data; 
      deferred.resolve(data); 
     }, 
     function(err) { 
      deferred.reject(err); 
     }); 
    return deferred.promise; 
    } 
    else { 
     return this.outData; 
    } 
} 
}); 
+0

作为您的来电是异步,你应该CONSOLE.LOG解决后,即'$ scope.mydata = service.getData()。然后(功能(用户){$ = scope.mydata(user.data );的console.log(($ scope.mydata)); }); ' –

+0

可以ü请修改我的代码,然后发表评论 –

+0

修改您的原始来源。请在您的控制器中使用修改后的源代码进行测试 –

回答

-1

$http.get().then()$http.get().success()不同。
你的代码改成这样:

var deferred = $q.defer(); 
$http.get('jsons/hassan.json') 
    .success(function(data){ 
     this.outData = data; 
     deferred.resolve(data); 
    }) 
    .error(function(err) { 
     deferred.reject(err); 
    }); 
return deferred.promise; 
+1

$ http已经是承诺,不需要推迟 – AlainIb

+2

'$ http.get()。success()'和'error()'不推荐使用(https://github.com /angular/angular.js/commit/b54a39e2029005e0572fbd2ac0e8f6a4e5d69014),你应该在v1.6.0中使用'then()'代替 – Andriy

+0

@Andriy!我相信他没有使用v1.6.0! –

1

改变控制器如下:

app.controller('showdata', function($scope, service){ 
    service.getData().then(function(user){ 
     $scope.mydata = (user.data); 
     console.log(($scope.mydata)); 
    }); 
}); 
3

$http本身是一种承诺,所以在$q没有必要,尝试重写使用$http代码的cache

app.controller('showdata', function($scope, service){ 
    service.getData().then(function(user) { 
    // no need to call user.data, service handles this 
    $scope.mydata = user; 
    console.log($scope.mydata); 
    }).catch(function (err) { 
    // handle errors here if needed 
    }); 
}); 

app.service('service', function($http){ 
    this.getData = function() { 
    return $http({ 
     method: 'GET', 
     url: 'jsons/hassan.json', 
     // cache will ensure calling ajax only once 
     cache: true 
    }).then(function (data) { 
     // this will ensure that we get clear data in our service response 
     return data.data; 
    }); 
    }; 
}}); 
+0

兄弟你正在调用控制器中的getData方法> service.getData不是一个函数 –