Quiero obtener el archivo carData.json
de un servidor usando AngularJS
.
Así es como lo he estructurado:
Tengo un archivo services.js
(dentro de la carpeta js
) donde guardo todos mis services
y factories
. Aquí está el factory
que uso para obtener el archivo carData.json
de un servidor:
carApp.factory('getAllCars', function($http){
return {
get: function() {
return $http.get('data/carData.json');
}
};
});
También tengo un controlador CarsByReviewCtrl
que usa el archivo carData.json
para sus propósitos:
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);
...
Y finalmente aquí está el final de mi archivo .html
donde paso estos archivos .js
. (He llamado al controlador en el medio de mi archivo html
)
<script type="text/javascript" src="js/controllers/CarsByReviewCtrl.js"></script>
<script type="text/javascript" src="js/services.js"></script>
</body>
</html>
Ahora, si ejecuto mi aplicación y abro la consola, obtendría el resultado de undefined
, en lugar del objeto javascript que obtuve del servidor.
¿Qué he hecho mal y cómo puedo solucionarlo?
2 respuestas
Está intentando imprimir el contenido de $scope.allCars
antes de que se resuelva la solicitud HTTP.
Agregó algunos comentarios a su código para explicar cómo debería leerlo:
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);
El problema es: console.log($scope.allCars)
se ejecuta antes de que se ejecute el controlador de éxito. puedes cambiar tu código a:
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 = [];
...
Preguntas relacionadas
Nuevas preguntas
javascript
Para preguntas sobre la programación en ECMAScript (JavaScript / JS) y sus diversos dialectos / implementaciones (excepto ActionScript). Incluya todas las etiquetas relevantes en su pregunta; por ejemplo, [node.js], [jquery], [json], etc.