我正在尝试遍历并按 id 进行搜索,并通过 Controller 中的 $resource 从如下所示类型的 JSON 对象返回与 id 对应的其他值。我不明白在这种情况下我哪里错了?请帮忙!
这是 Controller
appSettings.controller('applistController', ['$scope', 'AppListService',
function($scope, AppListService){
// Have to iterate here to search for an id, how?
// The Above app.json file is returned by the ApplistService(not showing the factory here as it works already.)
$scope.allapps = AppListService.listAllApps().get();
// console.log($scope.allapps.data) returns undefined as so does console.log($scope.allapps.length).
// Where am I wrong?
}
]);
JSON 的类型是:
{"data":[
{
"id":"files_trashbin",
"name": "TrashBin",
"licence":"AGPL",
"require":"4.9",
"shipped": "true",
"active":true
},
{
"id":"files_external",
"name": "External Storage",
"licence":"AGPL",
"require":"4.93",
"shipped":"true",
"active":true
}
],
"status":"success"
}
最佳答案
我想 AppListService.listAllApps().get();
会返回 promise。听起来您在获得实际数据之前尝试打印。
我会使用以下方法:
var appSettings = angular.module('myModule', ['ngResource']);
appSettings.controller('applistController', ['$scope', 'AppListService',
function($scope, AppListService){
AppListService.listAllApps()
.then(function (result) {
$scope.allapp = result;
}, function (result) {
alert("Error: No data returned");
});
}]);
appSettings.factory('AppListService', ['$resource','$q', function($resource, $q) {
var data = $resource('somepath',
{},
{ query: {method:'GET', params:{}}}
);
var factory = {
listAllApps: function () {
var deferred = $q.defer();
deferred.resolve(data);
return deferred.promise;
}
}
return factory;
}]);
关于javascript - 在 Angular 上迭代服务返回的 JSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19887626/