Javascript Angularjs:无法迭代或从服务结果获取结果
伙计们 我是Angularjs的新手,这里是我新的单页应用程序的一些代码。但我觉得我做得不对。 这是我的上帝:Javascript Angularjs:无法迭代或从服务结果获取结果,javascript,angularjs,Javascript,Angularjs,伙计们 我是Angularjs的新手,这里是我新的单页应用程序的一些代码。但我觉得我做得不对。 这是我的上帝: var TownApp=angular.module('TownApp',['ngRoute','ngResource']); TownApp.service('Town', function($http) { this.all = function() { return $http.get('/database.json').then(function(re
var TownApp=angular.module('TownApp',['ngRoute','ngResource']);
TownApp.service('Town', function($http) {
this.all = function() {
return $http.get('/database.json').then(function(response){
return response.data;
})
};
});
var HomeCtrl = TownApp.controller('HomeCtrl',function($scope,Town){
$scope.towns = Town.all();
});
var TownCtrl = TownApp.controller('TownCtrl',function($scope, $routeParams, Town){
console.log(Town.all().length)
$scope.towns = Town.all();
console.log($scope.towns.length)
//........
})
TownApp.config(['$routeProvider', function($routes) {
$routes.when('/',{
templateUrl : 'welcome.html',
controller : 'HomeCtrl'
}).when('/town/:townId',{
templateUrl : 'town.html',
controller : 'TownCtrl'
}).otherwise({
redirectTo : '/'
});
}]);
所以,问题是您可以在Town controller中看到这两个控制台日志,它们都返回“未定义”。因此,我无法迭代或从Town.all()
获取值。但它在HomeController上工作得非常完美
我在服务和工厂方面都做了很多工作。我想我只是做错了?
谢谢你的帮助 您的错误是,您试图以同步方式从服务器检索数据,这在angular(一般来说在javascript中也不起作用) 将服务代码更改为:
TownApp.service('Town', function($http) {
this.all = function() {
return $http.get('/database.json');
};
});
然后将控制器代码更改为:
TownApp.controller('HomeCtrl',function($scope,Town){
Town.all().then(function(response)) {
$scope.towns = response.data;
console.log($scope.towns.length);
}
}
Town.all()
返回一个承诺。承诺就像是将来某个时候要回报的价值。这不是直接的价值。它是一个可用于检索值的对象
所以不是
$scope.towns = Town.all();
你需要:
Town.all()
.then(function(response){
//if the promise we are dealing with is the promise that was directly
//returned from the $http call, then we need response.data
//if it was projected to hold `response.data` before (as in the initial question)
//then "response" here is already holding our data.
$scope.towns = response;
});
无需将Town.all()分配给
$scope.towns
Hi,Christoph,但response.data
正在返回undefined
:(@Still.Wang是的,这实际上取决于您之前如何投射承诺。如果您投射返回响应.data
,那么在下一步中,参数已经是您的响应数据。如果您接受从$http
调用返回的原始承诺,那么您需要获取响应.data
。但是根据o您的初始示例只需要响应
。我将在我的回答中更正这一点。嗨,Shay,我现在从控制台获得无法读取未定义的
的属性'length',您认为可能是什么问题?您是否检查了response.data中得到的内容。它可能不是您要查找的数组。请在t上设置断点他将$scope.towns=response.data;行并检查响应包含的内容。Iv将所有数据从异步更改为静态JSON字符串,节省了大量时间。我一定会在完成此项目后返回到异步服务内容。再次感谢您的帮助!