我想使用AngularJS
从服务器获取carData.json
文件。
以下是我的结构:
我有一个services.js
文件(在js
文件夹中),其中保存了我所有的services
和factories
。这是我用来从服务器获取carData.json
文件的factory
:
carApp.factory('getAllCars', function($http){
return {
get: function() {
return $http.get('data/carData.json');
}
};
});
我还有一个CarsByReviewCtrl
控制器,它使用carData.json
文件来实现它的目的:
carApp.controller("CarsByReviewCtrl", function($scope, getAllCars) {
getAllCars.get().success(function(data){
$scope.allCars = data;
}).error(function(data, status, headers, config) {
alert("AJAX failed")
});
$scope.carList = [];
console.log($scope.allCars);
...
最后是我的.html
文件的末尾,我在这里传递这些.js
文件。(我在html
文件中间调用了控制器)
<script type="text/javascript" src="js/controllers/CarsByReviewCtrl.js"></script>
<script type="text/javascript" src="js/services.js"></script>
</body>
</html>
现在,如果我运行我的应用程序并打开控制台,我将获得undefined
的输出,而不是从服务器获得的javascript对象。
我做错了什么?我该如何解决
您正试图在解析HTTP请求之前打印$scope.allCars
的内容。
在你的代码中添加了一些注释,以解释你应该如何阅读:
carApp.controller("CarsByReviewCtrl", function($scope, getAllCars) {
// first line of JS to be invoked
getAllCars.get().success(function(data){
// this will be executed later in time, after receiving the HTTP response (case success)
$scope.allCars = data;
}).error(function(data, status, headers, config) {
// this will be executed later in time, after receiving the HTTP response (case error)
alert("AJAX failed")
});
// this will be executed immediately after the previous JS line: getAllCars.get()
$scope.carList = [];
// this will be executed immediately after the previous JS line
console.log($scope.allCars);
问题是:console.log($scope.allCars)
在成功处理程序运行之前运行。您可以将代码更改为:
carApp.controller("CarsByReviewCtrl", function($scope, getAllCars) {
getAllCars.get().success(function(data){
$scope.allCars = data;
console.log($scope.allCars);
}).error(function(data, status, headers, config) {
alert("AJAX failed")
});
$scope.carList = [];
...