代码之家  ›  专栏  ›  技术社区  ›  diplosaurus

$http/$q/promise问题(Angular)

  •  0
  • diplosaurus  · 技术社区  · 9 年前

    当$q/$http触发 onReject

    假设我有一个基本的电话:

    $http.get('/users')
      .then(function(res) {
        return res.data;
      }, function(err) {
        console.log(err);
      });
    

    如果我得到 500 Internal Server Error 我会在 onSuccess 块从我对承诺的微薄理解来看,我想这似乎是正确的,因为我确实得到了回应?问题是 on成功 街区似乎是一个错误的地方

    if(res.status >= 400) {
      return $q.reject('something went wrong: ' + res.status);
    }
    

    只是为了让我 on拒绝 块将被运行。这是应该的工作方式吗?大多数人在 on成功 阻止或拒绝承诺 on拒绝 块我错过了更好的处理方法吗?

    我试着在一个 httpInterceptor 但我找不到办法从这里退回一个被拒绝的承诺。

    this.responseError = function(res) {
      if(res.status >= 400) {
        // do something
      }
    
      return res;
    };
    
    2 回复  |  直到 9 年前
        1
  •  1
  •   thllbrg    9 年前

    你的成功块不会被击中。尝试此操作,如果错误代码>300

    $http.get('/users').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.
      });
    
        2
  •  0
  •   Witold Cyrek    9 年前

    您可以在拦截器中而不是在回调中处理这些。

    在你的应用中。config您可以将$httpProvider配置为如下所示:

    $httpProvider.interceptors.push(['$q', function ($q) {
        return {
            request: function (config) {
                //do something 
                return config;
            },
            responseError: function (response) {
                if (response.status === 401) {
                    //handle 401
                }
                return $q.reject(response);
            }
        };
    }]);