codememo

Angular에서 $resource 메서드에 대한 콜백을 추가하는 방법JS

tipmemo 2023. 3. 4. 14:58
반응형

Angular에서 $resource 메서드에 대한 콜백을 추가하는 방법JS

사용자가 데이터를 업데이트/작성한 후 오류/성공 메시지를 표시해야 하는 일반적인 경우가 있을 수 있는데, 어떻게 하면 AngularJS에 구현할 수 있습니까?
콜백을 추가하고 싶지만 솔루션을 찾을 수 없습니다.$http.post ( success ) error ( )를 사용하는 것은 동작합니다만, 보다 높은 레버의 API $resource로 할 수 있을까요?
아니면 지시문을 작성해야 하나요 아니면 $watch()를 사용해야 하나요?
잘 부탁드립니다.

리소스 클래스의 액션은 하위 수준 $http 서비스와 마찬가지로 성공 및 오류 콜백을 전달할 수 있습니다.

문서에서

  • HTTP GET "class" 액션:Resource.action([파라미터], [성공], [오류])
  • GET 이외의 "클래스" 액션:Resource.action([파라미터], postData, [성공], [오류])

non-get 액션 앞에는$.

그러니까 네가 할 수 있어

User.get({userId:123}, function(u, getResponseHeaders){
  // this is get's success callback
  u.abc = true;
  u.$save(function(u, putResponseHeaders) {
    // This is $save's success callback, invoke notification from here
  });
});

편집: 이전 plunker의 다른 예를 보여 줍니다.get request는 존재하지 않는 json 파일을 요구하기 때문에 실패합니다.에러 콜백이 실행됩니다.

someResource.get(function(data){
    console.log('success, got data: ', data);       
}, function(err){
    alert('request failed');
});

최신 Angular 포함JS 버전에서는, 의 일부인 를 참조할 수 있습니다.$httpProvider.

그런 다음 전송 신호 수신 전 또는 응답 후에 모든 요청을 대행 수신할 수 있습니다.

angular.module('app').config(function($httpProvider){

  $httpProvider.interceptors.push(function($q) {
    return {
      'request': function(config) {
        console.log('I will send a request to the server');
        return config; 
      },

      'response': function(response) {
        // called if HTTP CODE = 2xx 
        console.log('I got a sucessfull response from server'); 
        return response;
      }

      'responseError': function(rejection) {
        // called if HTTP CODE != 2xx
        console.log('I got an error from server');
        return $q.reject(rejection);
      }
    };
  });

});

다시 돌아와야 합니다.config또는response작동시킬 수 있습니다.

의 경우rejection, 지연된 거부를 반환해야 합니다.$http.get().error()가로채고 나서도 여전히 작동중이야

언급URL : https://stackoverflow.com/questions/13852444/how-to-add-call-back-for-resource-methods-in-angularjs

반응형