服务没有从.json文件中向控制器提供数据



我想使用AngularJS从服务器获取carData.json文件。

以下是我的结构:

我有一个services.js文件(在js文件夹中),其中保存了我所有的servicesfactories。这是我用来从服务器获取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 = [];
    ...

最新更新