gpt4 book ai didi

javascript - 服务没有从 .json 文件中向 Controller 提供数据?

转载 作者:行者123 更新时间:2023-12-02 17:01:17 26 4
gpt4 key购买 nike

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

这是我的结构:

我有一个 services.js 文件(在 js forlder 内),其中保存了我的所有 servicesfactories。这是我用来从服务器获取 carData.json 文件的 factory:

carApp.factory('getAllCars', function($http){
return {
get: function() {
return $http.get('data/carData.json');
}
};
});

我还有一个 CarsByReviewCtrl Controller ,它使用 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 文件中间调用了 Controller )

        <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);

关于javascript - 服务没有从 .json 文件中向 Controller 提供数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25684304/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com