我想在資源上創建一個自定義操作,它將處理從服務器接收到的結果。角度資源響應攔截器
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;
}
}
}
}
);
})
;
但是,當我使用自定義操作時,我得到了未修改的結果,而不是處理。 下面是該預期的行爲(和評論相關錯誤)代碼:
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."
}));
});