我正在尝试访问从 Promise 对象返回的数组的长度。但是,我没有运气让它工作,因为当我检查数组本身时它返回未定义,并且我尝试访问它说无法读取属性的特定元素
从 Chrome 控制台
f {$promise: Object, $resolved: false, $get: function, $save: function, $query: function…}
$promise: Object
$resolved: true
address: "1600 amphitheatre way , Mountain View, CA 94043"
address_1: "1600 amphitheatre way "
address_2: "Mountain View, CA 94043"
affiliation_attributes: Array[0]
award_attributes: Array[0]
certification_attributes: Array[0]
description: ""
description_read_more: false
education_attributes: Array[1]
id: 1
lat: "37.422003"
lng: "-122.083978"
name: "Gio Wong"
phone: "650-701-6411"
photos: Array[3]
practice_name: "Super Doctor"
rating: null
rating_url: null
salutation: "DDS"
services: Array[4]
specialty: "Pediatrician"
__proto__: f
我正在尝试访问教育、隶属关系、奖励和认证属性。以下代码是我如何打印到控制台以及如何获取 Promise 对象
$scope.provider = Provider.get($routeParams.name);
console.log($scope.provider)
如何访问 $scope.provider.education_attributes.length?甚至 $scope.provider.education_attributes[0]?两者都返回无法读取属性。
最佳答案
提供者函数返回一个 Angular Promise 对象。它不会直接返回您的数据。相反,您为 Promise 提供一个函数,以便在 Promise 解决后调用。
你应该这样做:
Provider.get($routeParams.name).then(function(resolveData) {
//access stuff on resolveData here
});
请参阅 Angular's $q service 的“Promise API”部分.
关于javascript - 访问返回的 Promise 对象数组值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25394441/