在角度中,如果服务器响应{错误:'ok'},则$http去捕获

In angular make $http go to catch if server response with {error:'ok'}

本文关键字:ok http 如果 服务器 错误 响应      更新时间:2023-09-26
$http.get('/data.json')
.then(function(){console.log('ok'})
.catch(function(){console.log('no ok')})

服务器响应为:

200 OK
content-type: application/json
{error:'cannot get the data'}

我希望回应会去.catch而不是.then.

我知道我可以从服务器更改响应标头,但我只想在客户端执行此操作。

换句话说:

我如何使角度$http承诺服务,认为响应对象中带有"error"键的 200 OK 状态将转到catch而不是调用 then 函数?

您可以使用拦截器:

yourApp.factory('myInterceptor', ['$q', function($q) {
  return {
    response: function(response) {
      if (response.status === 200 && response.data.error) {
        return $q.reject(response);
      }
      else {
        return response;
      }
    }
  };
}]);
$httpProvider.interceptors.push('myInterceptor');
$http.get('/data.json')
.then(function(res){
   if(res.error === 'cannot get the data'){
     return $q.reject(res)
   }
   return res;
)
.then(function(){console.log('ok'})
.catch(function(){
   console.log('no ok')
})

正如其他人建议的那样,您可以使用角度$q服务reject()函数检查您希望将请求视为.then块内的失败并拒绝的条件

正如@yarons指出的,你可以使用拦截器。但是,你的决定是始终返回 200,即使在error的情况下,那么为什么你现在想在前端改变这种行为呢?

你的逻辑似乎是这样的:

不要告诉前端抛出错误(也许不显示在 开发控制台或让用户现在(,但在内部将其作为 错误。

对我来说,如果你决定采取这种技巧行为,那就一路走下去,不要四处乱窜。只需在then()中查找错误消息即可。

因此,按照您的计划进入then(),然后用if子句在那里捕获您的错误:

$http.get('/data.json')
.then(function(response){
    if(response.data.error) {
       $scope.error_message = response.data.error;
       return;
    }
});