2013-07-02 2 views
11

나는 PHP로 만든 간단한 REST 서버와 다시 대화하기 위해 각도 서비스를 만들었다. 단일 레코드, 모든 레코드 목록 및 새 레코드 추가 기능을 사용할 수 있음을 알 수 있습니다. 그러나 새 레코드를 추가 한 후에 서버에서 올바른 응답을 얻는 데 문제가 있습니다.AngularJS with ngResource : 서버의 정확한 응답을 확인하는 방법은 무엇입니까?

나는 새로운 레코드를 추가하기 때문에, 그러나, 나는 어떤 이유 요청 등 작동하지 않을 경우 사용자에 대한 알림을 넣어하고자 일하고 알고 ...

서비스는 다음과 같습니다

컨트롤러의 일환으로
angular.module('adminApp.services', ['ngResource']) 

    .factory('Settings', function($resource) { 

     return $resource('rest/setting/:id', {id: '@id'}, { 
      'query' : { method: 'GET', params: {}, format: 'json', isArray: true }, 
      'save' : { method: 'POST', params: {}, format: 'json', isArray: true }, 
      'get' : { method: 'GET', params: {}, format: 'json', isArray: false }, 
      'update': { method: 'PUT', params: {id: '@id'}, format: 'json', isArray: true }, 
      'delete': { method: 'DELETE', params: {id: '@id'}, format: 'json', isArray: false } 
    }); 

}); 

, 나는 다음과 같습니다

$scope.save = function() { 
    var result = Settings.save({}, $scope.settings); 

    console.log(result); 

    // Here I would like to send the result to the dialog 
    // to determine wether or not the request was successful 
    // dialog.close(result); 
}; 

자바 스크립트 콘솔 retur를 통해 볼 때 HTTP 요청에서 네트워크 응답, ns 'true'는 서버에서 돌아 오지만 console.log (result)는 'true'의 문자 배열을 반환합니다. isArray : true 옵션이 'save'에 있기 때문에 추측했습니다. params 객체를 파라미터는하지만 배열로 서버에 전송받을 필요가 있기 때문에 :

[$promise: Object, $resolved: false] 
    0: "t", 
    1: "r", 
    2: "u", 
    3: "e", 
    $promise: Object, 

    // I tried passing result.$resolved to the dialog, 
    // but if yousee above it resolves to false up top first 
    $resolved: true, 
    length: 4, 
    __proto__: Array[0] 

나는 쉽게 될 것이라고으로 훅 수 있다면 (내가 jQuery를 배경에서 온 HTTP 응답이 사실의 JSON 값을 알고 , 어쩌면 내가 잘못하고있다, 나는 그것을 jQuery를이 프로젝트에서 완전히 제거하여 내 학습을 방해하지 못하게했다.)

나는 실제적으로 사용할 수있는 JS 변수에 서버로부터의 응답을 어떻게 실제로 얻을 수 있을까?

편집 : 업데이트

나는 내 서비스를 변경 :

angular.module('adminApp.services', ['ngResource']) 
    .factory('Settings', function($http, $resource, $log) { 
     return $resource('rest/setting/:id', {id: '@id'}, { 
      save : { 
      method: 'POST', 
      params: {}, 
      format: 'json', 
      isArray: true, 
      transformResponse: [function(data, headersGetter) { 
       $log.info(data); // returns true 
       return { response: data }; 
      }].concat($http.defaults.transformResponse) 
     }, 
     update : { method: 'PUT', params: {id: '@id'}, format: 'json', isArray: true }, 
     delete : { method: 'DELETE', params: {id: '@id'}, format: 'json', isArray: false } 
    }); 

}); 

그리고 호출 :

$scope.save = function() { 
    $scope.results = Settings.save({}, $scope.settings); 
    console.log($scope.results); // Still returns the response with $promise 
    //dialog.close(true); 
}; 

하지만 여전히 응답

참으로받지 못했습니다
+0

나는이 문제를 이해하기를 바랍니다. 두 개의 콜백을'Settings.save' 호출에 추가해보십시오. 성공과 실패 콜백입니다. 여기를 참조하십시오 : http://docs.angularjs.org/api/ngResource.$resource. 두 번째 콜백에서 오류 코드를 표시 할 수 있다고 가정합니다. – akonsu

+0

나는 전송 된 데이터가 배열이되도록 isArray가 필요 없다고 확신한다. 반환 값 해석을 수정한다. http://docs.angularjs.org/api/ngResource.$resource – shaunhusain

+0

@shaunhusain isArray : false push 변수를 사용할 수 없음을 알리는 오류가 발생합니다. 일부 인터넷 검색은 this에 isArray : true를 추가하여 해결 된 것으로 나타났습니다. –

답변

13

이 부분을 참조하십시오.

angular.module('myApp', ['ngResource']). 
factory('myService', function($http, $resource, $log){ 
    return $resource('/', {}, { 
     get: { 
      method: 'GET', 
      transformRequest: [function(data, headersGetter){ 
       // you can examine the raw request in here 
       $log.info(data); 
       $log.info(headersGetter()); 
      }].concat($http.defaults.transformRequest), 
      transformResponse: [function (data, headersGetter) { 
       // you can examine the raw response in here 
       $log.info(data); 
       $log.info(headersGetter()); 
       return {tada:"Check your console"}; 
      }].concat($http.defaults.transformResponse) 
     } 
    }); 
}). 
controller('myController', function(myService, $scope, $resource, $http, $log) { 
    $scope.results = myService.get(); 
}); 
0은 $ httpProvider.defaults.transformRequest 및 $ httpProvider.defaults.transformResponse 속성을 수정, 기능 보강을 전역 또는 기본 변환을 무시합니다.

자세히 알아보기 : http://docs.angularjs.org/api/ng.$ http

+0

아 참 매우 멋지므로 클라이언트 측에서 "인터셉터"와 같은 것을 허용합니까? – shaunhusain

+0

수정. 글로벌 인터셉터를 원한다면, 그것을 당신의 app config의 $ httpProvider에 추가 할 수 있습니다. –

+0

나는 당신의 바이올린을 시험해 보았고 나의 답을 수정하려했지만 여전히 문제가 있습니다. 좀 봐 주시겠습니까? 나는 컨트롤러 끝에서 변형 된 응답을 얻지 못하기 때문에 뭔가 잘못하고있을 것입니다. –

0

안녕하세요 알고 있지만 다른 사람들에게 도움이 될 수도 있습니다. 배열에 대한 응답 변환의 이유는 각도 리소스가 응답의 "데이터"속성을 예상하고 그 이후에 각 요소에 대해 반복합니다. 당신이 "데이터"개체 이상이

response = { 
    data: true 
    } 

다음 각도-자원으로 반복 같은 서버에서 데이터 속성 내부에 문자열을 전송 등 데이터의 배열을 만드는 경우 "데이터"하지만, 올바른 방법은 응답을 보내는 것입니다 이게 뭐니?

response = { 
    data: {users: users} // Or any other property but not directly data 
    } 

감사합니다.

관련 문제