循环的Javascript Web API调用
我正在用angularjs和ionic开发一个应用程序。 这里有一个ID为的数组。从这些ID中我需要一个名字。现在我用下面的代码进行了尝试:循环的Javascript Web API调用,javascript,angularjs,asp.net-web-api,Javascript,Angularjs,Asp.net Web Api,我正在用angularjs和ionic开发一个应用程序。 这里有一个ID为的数组。从这些ID中我需要一个名字。现在我用下面的代码进行了尝试: var arrayWithIds = [1, 2, 3, 4, 5, 6, 7] var arrayWithNames = []; for (var j = 0; j < arrayWithIds.length; j++) { ResourceService.get(arrayWithIds[j]).then(function(resour
var arrayWithIds = [1, 2, 3, 4, 5, 6, 7]
var arrayWithNames = [];
for (var j = 0; j < arrayWithIds.length; j++) {
ResourceService.get(arrayWithIds[j]).then(function(resource) {
arrayWithNames.push(resource.Name);
},function(error) {
alert(error.message);
});
}
$scope.resources = arrayWithNames;
var arraywhithids=[1,2,3,4,5,6,7]
var arrayWithNames=[];
对于(var j=0;j
调试时一切正常。我总是能找回这个名字。但是在$scope.resources中没有任何内容,它是空的,还有数组arrayWithNames
我错过什么了吗?有什么问题
谢谢。ResourceService.get()调用是异步的(也是一个承诺),这一行
$scope.resources = arrayWithNames;
在ResourceService.get()回调之前调用
您可以删除带有名称的数组,并直接推送到$scope。参考资料
:
var arrayWithIds = [1, 2, 3, 4, 5, 6, 7]
$scope.resources = [];
for (var j = 0; j < arrayWithIds.length; j++) {
ResourceService.get(arrayWithIds[j]).then(function(resource) {
$scope.resources.push(resource.Name);
},function(error) {
alert(error.message);
});
}
var arraywhithids=[1,2,3,4,5,6,7]
$scope.resources=[];
对于(var j=0;j
您是否尝试过添加带有名称的返回数组;在for循环的末尾?看看这是否有效?谢谢你的回答。我已经试过了,但没有成功。也许有一点很重要,上面的整个代码也在一个web api调用中。请检查响应变量名。是名字还是名字。@Ramesh:非常感谢。这就是问题所在。