itsource

각 $http 서비스에서는 오류 상태를 파악하려면 어떻게 해야 합니까?

mycopycode 2023. 2. 14. 20:18
반응형

각 $http 서비스에서는 오류 상태를 파악하려면 어떻게 해야 합니까?

'Pro Angular JS'라는 책을 읽고 있어요.그러나 에러 상태를 어떻게 파악해야 하는지 질문이 있습니다.

코드화한 것은 다음과 같습니다.

$http.get(dataUrl)
    .success(function (data){
        $scope.data.products = data;
    })
    .error(function (error){
        $scope.data.error=error;
        console.log($scope.data.error.status); // Undefined!
        // (This is the spot that I don't get it.)                                         
    });

console.log($scope.data.error.status);"를 코드화하면 console.log의 인수가 정의되지 않는 이유는 무엇입니까?

책에는 "오류 함수에 전달된 객체가 상태 및 메시지 속성을 정의합니다."라는 문장이 있습니다.

그래서 $scope.data.error.status를 실행했습니다.

왜 틀렸을까요?

$http레거시 약속 방식success그리고.error더 이상 사용되지 않습니다.표준 사용then대신 메서드를 사용합니다.https://docs.angularjs.org/api/ng/service/$http 문서를 참조해 주세요.

올바른 사용 방법은 다음과 같습니다.

// Simple GET request example:
$http({
  method: 'GET',
  url: '/someUrl'
}).then(function successCallback(response) {
    // this callback will be called asynchronously
    // when the response is available
  }, function errorCallback(response) {
    // called asynchronously if an error occurs
    // or server returns response with an error status.
});

응답 개체에는 다음 속성이 있습니다.

  • 데이터 – {string|Object} – 변환 함수를 사용하여 변환된 응답 본문.
  • status – {number} : 응답의 HTTP 상태 코드.
  • 헤더 – {function([headerName])} – 헤더게터 기능
  • config – {Object} : 요청을 생성하기 위해 사용된 설정 객체.
  • statusText: {string}: 응답의 HTTP 상태 텍스트.

200 ~ 299 의 응답 상태 코드는 성공 상태로 간주되어 성공 콜백이 호출됩니다.

인수가 올바르지 않습니다. 오류는 상태와 메시지를 포함하는 개체를 반환하지 않습니다. 인수는 아래에 설명된 순서대로 별도의 매개 변수로 전달했습니다.

각도 도큐에서 가져온 내용:

  • 데이터 – {string|Object} – 변환 함수를 사용하여 변환된 응답 본문.
  • status – {number} : 응답의 HTTP 상태 코드.
  • 헤더 – {function([headerName])} – 헤더게터 기능
  • config – {Object} : 요청을 생성하기 위해 사용된 설정 객체.
  • statusText: {string}: 응답의 HTTP 상태 텍스트.

따라서 코드를 다음과 같이 변경해야 합니다.

$http.get(dataUrl)
    .success(function (data){
        $scope.data.products = data;
    })
    .error(function (error, status){
        $scope.data.error = { message: error, status: status};
        console.log($scope.data.error.status); 
  }); 

당연히 오류를 나타내는 개체를 만들 필요는 없습니다.단, 개별 범위 속성만 만들 수 있지만 동일한 원칙이 적용됩니다.

업데이트: angularjs 1.5 현재 약속 메서드의 성공과 오류는 권장되지 않습니다.( 답변 참조)

현재 문서에서:

$http.get('/someUrl', config).then(successCallback, errorCallback);
$http.post('/someUrl', data, config).then(successCallback, errorCallback);

함수의 다른 인수를 다음과 같이 사용할 수 있습니다.

error(function(data, status, headers, config) {
    console.log(data);
    console.log(status);
}

$140 문서 참조:

// Simple GET request example :
$http.get('/someUrl').
  success(function(data, status, headers, config) {
    // this callback will be called asynchronously
    // when the response is available
  }).
  error(function(data, status, headers, config) {
    // called asynchronously if an error occurs
    // or server returns response with an error status.
  });

★★$http.get 더 높은 「됩니다.success ★★★★★★★★★★★★★★★★★」error하다)then(각선) 을 누릅니다.

$http.get('/someUrl')
    .then(function success(response) {
        console.log('succeeded', response); // supposed to have: data, status, headers, config, statusText
    }, function error(response) {
        console.log('failed', response); // supposed to have: data, status, headers, config, statusText
    })

든지 "My version of Angular is docs"를 수 .arguments적절한 메서드의 시그니처를 모르는 경우라도, 다음의 순서에 따릅니다.

$http.get('/someUrl')
  .success(function(data, foo, bar) {
    console.log(arguments); // includes data, status, etc including unlisted ones if present
  })
  .error(function(baz, foo, bar, idontknow) {
    console.log(arguments); // includes data, status, etc including unlisted ones if present
  });

그런 다음 검색한 내용을 기반으로 함수 인수를 일치시킬 수 있습니다.

공식 각도 문서에서

// Simple GET request example :
$http.get('/someUrl').
  success(function(data, status, headers, config) {
    // this callback will be called asynchronously
    // when the response is available
  }).
  error(function(data, status, headers, config) {
    // called asynchronously if an error occurs
    // or server returns response with an error status.
  });

에러 콜백의 첫 번째 파라미터는 데이터이며 상태는 두 번째입니다.

응답 상태는 (docs에서) 콜백의 두 번째 파라미터로 표시됩니다.

// Simple GET request example :
$http.get('/someUrl').
  success(function(data, status, headers, config) {
    // this callback will be called asynchronously
    // when the response is available
  }).
  error(function(data, status, headers, config) {
    // called asynchronously if an error occurs
    // or server returns response with an error status.
  });

언급URL : https://stackoverflow.com/questions/27507678/in-angular-http-service-how-can-i-catch-the-status-of-error

반응형