3

我在使用 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

4

1 回答 1

5

您没有处理 $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
});
于 2014-04-25T21:28:38.560 回答