Pav*_*ala 3 rest angularjs ngresource
我在使用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;
});
Run Code Online (Sandbox Code Playgroud)
这是我在使用$ resource的同一请求时失败的attemt:
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);
Run Code Online (Sandbox Code Playgroud)
编辑:更新上面的代码后,这是我在控制台中得到的.
f {$promise: Object, $resolved: false, $get: function, $save: function, $query: function…}
$promise: Object
$resolved: true
error: false
topics: Array[10]
__proto__: f
Run Code Online (Sandbox Code Playgroud)
但是,如果我将控制台日志更改为:
console.log(response.topics);
Run Code Online (Sandbox Code Playgroud)
控制台只返回:
undefined
Run Code Online (Sandbox Code Playgroud)
我哪里错了?如果它有助于链接到相关页面http://hwaelapps.com/discuss/web
你没有处理$ 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
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
6739 次 |
| 最近记录: |