在AngularJS中,可以使用$http服务来发送GET请求获取数据。如果在使用$http GET请求获取数据时,$scope.names始终是一个空数组,但与后端的调用是正常的,可能有以下几种解决方法:
确保后端返回的数据是正确的:在浏览器的开发者工具中查看请求的响应,确保后端返回的数据是非空的,并且是正确的。
使用回调函数处理异步请求:由于$http是异步请求,需要使用回调函数来处理返回的数据。确保将获取到的数据赋值给$scope.names数组,在回调函数中进行操作,例如:
$http.get('api/names').then(function(response) {
$scope.names = response.data;
});
app.controller('MyController', function($scope, $http) {
$scope.init = function() {
$http.get('api/names').then(function(response) {
$scope.names = response.data;
});
};
});
app.config(function($routeProvider) {
$routeProvider.when('/', {
templateUrl: 'views/home.html',
controller: 'HomeController',
resolve: {
namesData: function($http) {
return $http.get('api/names').then(function(response) {
return response.data;
});
}
}
});
});
app.controller('HomeController', function($scope, namesData) {
$scope.names = namesData;
});
以上是几种可能的解决方法,根据具体情况选择适合的方法来解决$scope.names为空的问题。