Angular $ httpProvider拦截器和$资源

时间:2016-06-28 20:08:17

标签: javascript angularjs http resources interceptor

我有一个简单的角度拦截器拦截请求并添加授权头。它还拦截401的响应错误,以了解请求是否因授权而失败。

不幸的是,它似乎搞乱了$ resource,因为我的$ resource调用ALWAYS返回成功回调而且从不出错(无论是400还是500)。

它绝对是拦截器,因为如果我删除它,$ resource调用将返回正确的回调。

有关如何解决此问题的任何想法?

这是拦截器请求:

  function request(config) {
    var token = 'whatever-my-token-is';

    if (token) {
      config.headers.authorization = token;
    }

    return config;
  }

还有responseError:

function responseError(response) {
  if (response.status === 401) {
    $rootScope.$broadcast('unauthorized');
  }

  return response;
}

任何帮助表示赞赏

1 个答案:

答案 0 :(得分:0)

我认为您需要使用承诺来返回错误 将$q添加到您的Interceptor工厂。 像这样

$provide.factory('MyHttpInterceptor', function ($q){
   ...
})

然后有responseError()

function responseError(response) {
  if (response.status === 401) {
    $rootScope.$broadcast('unauthorized');
  }

 return $q.reject(response);
}

此链接也可能有助https://djds4rce.wordpress.com/2013/08/13/understanding-angular-http-interceptors/

相关问题