Car*_*ing 4 javascript callback angularjs
我的问题与这里的问题非常相似:如何将值传递给AngularJS $ http成功回调
根据Angular.js
$ http遗留承诺方法成功和错误已被弃用.请改用标准方法.
那么怎么样,只用.then做类似的事情呢?
在我的服务中,我的代码是碎片式的
fetchFromAPI: function(key) {
return $http.jsonp(...);
}
Run Code Online (Sandbox Code Playgroud)
这是我的控制者
for (var i = 0; i < units.length; i++){
Service.fetchFromAPI(i)
.then(function(response) {
console.log(i);
}, function(response) {
console.log(response);
});
}
Run Code Online (Sandbox Code Playgroud)
但是由于在返回任何调用之前的for循环完成执行,控制台的输出是相同的数字,我无法绕过上面编写类似于.success示例的上述内容,我的所有尝试都给了我我的控制器不是函数的错误.
Jim Horng发布的解决方案是
$http.get('/plugin/' + key + '/js').success((function(key) {
return function(data) {
console.log(key, data);
}
})(key));
Run Code Online (Sandbox Code Playgroud)
只需使用内置 angular.forEach
angular.forEach(units, function(unit, index){
Service.fetchFromAPI(unit)
.then(function(response) {
console.log(unit, response);
}, function(response) {
console.log(response);
});
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1593 次 |
| 最近记录: |