【问题标题】:Extracting data from angularJS $resource从 angularJS $resource 中提取数据
【发布时间】:2014-06-11 18:11:50
【问题描述】:

我在使用 Angular 的 $resource 服务时遇到问题。由于我的 API 会发回完整的响应(标头等)以及数据对象中的错误字段,因此我需要从响应中获取特定对象。使用 $http 服务执行此操作相当简单,但我不明白在哪里使用 $resource 服务获取这些参数。下面是有效的 $http 请求。

$http({
  method  : 'GET',
  url     : 'http://api.discussorama.com/v1/topics',
  headers : {'X-Api-Secret': 'xxx', 'Authorization': 'xxx', 'Content-Type': 'application/x-www-form-urlencoded'}  
})
.then(function(response) {
  console.log(response);
  $scope.topics = response.data.topics;
});

这是我对 $resource 的同一请求的失败尝试:

var Topic = $resource('http://api.discussorama.com/v1/topics/:id', {id: '@id'}, {
  query: {
    isArray: false,
    method: 'GET',
    headers: {'X-Api-Secret': 'xxx', 'Authorization': 'xxx', 'Content-Type': 'application/x-www-form-urlencoded'}
  }
 });

var response = Topic.query();
$scope.topics = response.topics;
console.log(response);

编辑:更新上述代码后,这是我在控制台中得到的。

f {$promise: Object, $resolved: false, $get: function, $save: function, $query:    function…}
  $promise: Object
  $resolved: true
  error: false
  topics: Array[10]
  __proto__: f

但是,如果我将控制台日志更改为:

console.log(response.topics);

控制台简单地返回:

undefined

我在哪里做错了?如果有帮助,则指向相关页面的链接是http://hwaelapps.com/discuss/web

【问题讨论】:

    标签: angularjs rest ngresource


    【解决方案1】:

    你没有处理 $resource 交还的承诺。它需要像上面的 $http 调用一样处理。

    var Topic = $resource('http://api.discussorama.com/v1/topics/id', { id: '@id'}, {
      query: {
        isArray: false,
        method: 'GET',
        headers: {'X-Api-Secret': 'xxx', 'Authorization': 'xxx', 'Content-Type': 'application/x-www-form-urlencoded'}
      }
    });
    
    var response = Topic.query();
    response.$promise.then(function(data){
        $scope.topics = data.topics; //Changed data.data.topics to data.topics
    });
    

    【讨论】:

    • 奇怪的是我得到了上面的代码:TypeError:无法读取未定义的属性'then'。我还使用控制台中的更多数据更新了问题。也许还有更多的东西可以解释我的情况。
    • 如果有可能的话,主题数据似乎是在承诺之外返回的。
    • 抱歉,忘记了promise前面的$。答案已更新。 (我在日常使用中有这种模式,所以你会认为我会记住它。)
    • 非常感谢。这解决了我的问题。我将您的代码从 data.data.topics 调整为 data.topics。我可能在我原来的问题中解释错了。再次感谢。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-05-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多