I’m making a single-page app with AngularJS and a Flask/Python backend that uses MongoDB. I’m having trouble showing data from the backend in the frontend. I can send an Angular $http GET request and see the result in the console, but the data doesn’t appear on the page. When I use a hardcoded JSON array in the factory, everything works perfectly, and I can even retrieve the data using curl. I’ve tried setting up a controller and a factory like this:
.controller('mainCtrl', function(dataService, $scope) {
var vm = this;
vm.items = dataService.getItems();
})
.factory('dataService', function($http) {
var service = {};
service.getItems = function() {
return $http.get('/api/items').then(function(response) {
return response.data;
});
};
return service;
});
And this is how I display the data:
<div ng-repeat="item in vm.items">
<h3>{{item.name}}</h3>
<p>{{item.description}}</p>
</div>
Any ideas on why the data isn’t showing up? Thanks for any help!
I encountered a similar issue in my project. The problem lies in the asynchronous nature of the $http request. To resolve this, modify your controller to handle the promise correctly:
.controller('mainCtrl', function(dataService, $scope) {
var vm = this;
vm.items = [];
dataService.getItems().then(function(data) {
vm.items = data;
}).catch(function(error) {
console.error('Error fetching items:', error);
});
})
This approach ensures that vm.items is updated once the data is retrieved. Also, consider implementing error handling to improve robustness. If the issue persists, verify your API endpoint and check for any CORS-related problems.
ooh, interesting problem! have u tried using $q.all() to handle multiple promises? also, maybe double-check ur API endpoint? sometimes the issue’s on the backend. btw, how r u handling errors? curious to hear more about ur setup!
hey mate, ran into this before. ur problem’s probs cuz getItems returns a promise, not the actual data. try this in ur controller:
dataService.getItems().then(function(data) {
vm.items = data;
});
that should fix it. lmk if u need more help!