2014-03-27 3 views
0

서버에서받은 결과를 처리하는 리소스에 대한 사용자 지정 동작을 만들려고합니다.각도 리소스 응답 인터셉터

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." 

    })); 
}); 

답변

0

은 "요격"아이디어 주셔서 감사합니다 : 다음은 코드 (관련 오류 및 주석) 예상 동작을 보여주는 것입니다! 속성 배열 "데이터"로, 응답 객체를 반환해야 내 의견

response.data = [5, 6]; // for simplifity 
return response; 

에서

, 그래서

result.length; 

가 실패합니다.

자원 응답의 결과를 조작하려면 응답을 사용하십시오. 자원 대신 response.data는 - (CRUD 방법과) 실제 REST 객체가

0

어쩌면이 ($http를 주입하는 기억)과 같은 새로운 transformResponse 변환을 추가하는 것입니다 필요, 당신은 쉽게 그렇게 할 수 있습니다 :

transformResponse: $http.defaults.transformResponse.concat([ 
    function (data, headersGetter) { 
     return data.objects 
    } 

차이는 인터셉터의 반환 값 result.$promise

해결되는 값 동안 resultresponse.resource 의해 치환 될이며
관련 문제