鉴于看起来是相同的资源对象,如下所示,由两个不同的路径生成,由于某种原因,这些对象的行为不一致 - 在一种情况下,我可以成功检索数组 ['values-response'] ['distinct-value'] 而在另一种情况下,当我尝试时,我会得到“未定义”。
在服务中对 $q.all()
返回的 Promise 使用 then()
方法后,将以下内容写入控制台:
Resource
$promise: Object
$resolved: true
values-response: Object
> distinct-value: Array[64]
metrics: Object
name: "term"
type: "xs:string"
为什么我无法将不同值数组分配给 ng-repeat
中使用的范围?在更改代码以使用 Promise 之前,我能够在 $resource
get()
方法的回调中执行此操作:
$scope.topics = data['values-response']['distinct-value'];
然后我可以在模板的 ng-repeat
中使用 data-ng-repeat="topic in topic"
。
但是,自从切换到 promise 后,如果我尝试这样做:
$scope.topics = data.topics['values-response']['distinct-value'];
然后控制台返回“未定义”,尽管根据上面的输出,它似乎已解决。
相反,我需要这样做:
$scope.topics = data.topics;
然后访问ng-repeat
中的数组,如下所示,我不确定它是否已优化:
<button data-ng-repeat="topic in topics['values-response']['distinct-value'] | filter:textFilter | orderBy:browseOrder:browseDirection as resultsTopics" class="btn btn-default" type="button">
JSON 由 MarkLogic REST API 返回。我认为没有必要,但以防万一我尝试了 angular.fromJson() 却无济于事。
更完整的代码图片(使用简化的代码片段)如下:
app.factory('BrowseService', [
'$q', '$resource',
function($q, $resource) {
var r = $resource('http://localhost\\:8005/LATEST/values/:facet', {
format: 'json',
options: 'browse'
});
var p1 = r.get({
facet: 'term'
});
var p2 = r.get({
facet: 'place'
});
var p3 = r.get({
facet: 'person'
});
return $q.all({
topics: p1,
places: p2,
people: p3
});
}
]);
app.controller('browseController', function($scope, BrowseService) {
$scope.browseOrder = '_value';
$scope.browseDirection = '';
$scope.textFilter = '';
$scope.people = [];
$scope.places = [];
$scope.topics = [];
BrowseService.then(function(data) {
$scope.topics = data.topics;
});
});
在从工厂返回 $q.all()
之前,以下操作已成功:
Browse.get({
facet: 'term'
}, function(data) {
$scope.topics = data['values-response']['distinct-value'];
});
<button data-ng-repeat="topic in topics | filter:textFilter | orderBy:browseOrder:browseDirection as resultsTopics" class="btn btn-default" type="button">
预先感谢您的帮助。
最佳答案
.get/.post
和.then
的成功回调参数是有区别的。 .then
function(result){} result.data
类似于 .get/.post
中的 result
尝试
BrowseService.then(function(results) {
$scope.topics = results.data.topics;
$scope.$apply();
});
也不确定它的拼写错误或者您错过了您使用的 .get
$scope.topics = data['values-response']['distinct-value'];
和.then
$scope.topics = data.topics['values-response']['distinct-value'];
检查您在响应中添加的 topics
属性
关于javascript - 在 AngularJS 中,为什么我无法将资源 promise 的回调中的数组分配给 Controller 中的范围?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30142572/