我有一个 angularjs
服务,让我的 JSON
数据。
I have an angularjs
service to get my json
data.
// Controller.js file
$scope.data=Events.query();
$scope.getEventtypes = function(){
angular.forEach($scope.data,function(value, key){
var arr = [];
if(key==$scope.month+$scope.year) {
for(var i=0; i<key.length; i++) {
arr.push(value[i].type);
$scope.eventtypes=arr.unique();
}
}
});
};
而试图访问值[I] .TYPE
它抛出一个错误的无法读取属性键入
未定义。我知道那是因为异步调用的。
while trying to access the value[i].type
it throws an error cannot read property type
of undefined. I know it is because of the asynchronous call.
//i want to add success function like this
$http.get('').success(function(data) {
....
});
谁能帮助我?它会更好,如果ü建议做一些比这更有效。谢谢
can anyone help me?? it will be better if u suggest to do something more efficient than this. Thank you
虽然@Mahbub的建议是朝着正确的方向(承诺使其更容易协调异步函数),它并不是唯一的方法。好,老回调将正常工作。虽然承诺可以说是更优雅的API一个严酷的事实是,承诺API不支持在目前,他的AngularJS版本的 $资源
的一部分。
While @Mahbub suggestion is in the right direction (promises make it easier to coordinate asynchronous functions) it is not the only technique. Good, old callbacks will work as well. While promises are arguably more elegant API the bitter truth it that promises API is not supported as part of the $resource
in he current version of AngularJS.
理论不谈,在特定情况下,你可以简单地使用一个回调,并用它来完成:
Theory aside, in your particular case you could simply use a callback and be done with it:
$scope.data=Events.query(function(data){
angular.forEach(data,function(value, key){
var arr = [];
if(key==$scope.month+$scope.year) {
for(var i=0; i<key.length; i++) {
arr.push(value[i].type);
$scope.eventtypes=arr.unique();
}
}
});
});