我想要创建一个对资源的自定义操作,它将处理从服务器接收的结果。
angular.module('problem', ['ngRoute', 'ngResource'])
.factory('Abc', function ($resource) {
return $resource('api/abc/:abcId', {abcId: '@id'}, {
customQuery: {
method: "GET",
isArray: true,
interceptor: {
response: function (response) {
// some operations that manipulate data based od response
response.data = [5, 6]; // for simplifity
console.log("manipulation finished"); // log is saved
return response;
}
}
}
}
);
})
;但是当我使用Custom时,我得到未经修改的结果,而不是处理结果。下面的代码显示了预期的行为(以及注释中的相关错误):
describe('Abc', function () {
beforeEach(module('problem'));
var $httpBackend;
beforeEach(function () {
angular.mock.inject(function ($injector) {
$httpBackend = $injector.get('$httpBackend');
})
});
it('should return converted array when customQuery called', inject(function (Abc) {
$httpBackend
.expectGET('api/abc')
.respond([
{id: 'uid1', name: 'name1'},
{id: 'uid2', name: 'name2'},
{id: 'uid3', name: 'name3'},
{id: 'uid4', name: 'name4'}
]);
var result = Abc.customQuery();
$httpBackend.flush();
expect(result.length).toBe(2); // fails with "Expected 4 to be 2."
expect(result[0]).toBe(5); // fails with "Expected { id : 'uid1', name : 'name1' } to be 5."
expect(result[1]).toBe(6); // fails with "Expected { id : 'uid2', name : 'name2' } to be 6."
}));
});发布于 2015-04-14 14:24:37
也许您需要添加一个新的transformResponse转换,您可以很容易地这样做(记住要注入$http):
transformResponse: $http.defaults.transformResponse.concat([
function (data, headersGetter) {
return data.objects
}不同的是,result将被response.resource取代,而拦截器的返回值是解析result.$promise的值。
发布于 2014-10-07 08:05:16
谢谢你的“拦截器”主意!
照我的想法
response.data = [5, 6]; // for simplifity
return response;应该返回带有属性数组"data“的响应对象,因此
result.length;应该会失败。
为了更好地操作资源响应的结果,最好使用response.resource而不是response.data --有真正的REST对象(使用CRUD方法)
https://stackoverflow.com/questions/22689683
复制相似问题