AngularJS错误代码401处理没有拦截器?

时间:2015-02-28 18:21:53

标签: angularjs angular-http angular-http-interceptors angular-http-auth

以下是我使用的代码,如果基本身份验证成功,我会收到身份验证成功警报但是其他警报"身份验证失败"凭据错误时永远不会显示。我没有使用任何路线,我也不需要使用拦截器。有没有办法在不使用拦截器的情况下获得401错误?

this.authorize = function(request, callbackFunc) {
  var encodedString = btoa(request.userName + ":" + request.password);
  var basicAuthString = 'Basic ' + encodedString;
  var requestObject = {
    location: '40005'
  };
  var req = {
    method: this.method,
    crossDomain: true,
    url: this.loginURL,
    data: requestObject,
    headers: {
      'Authorization': basicAuthString,
      'Content-Type': 'application/json',
      'Accept': '*/*',
      'apiKey': ''
    }

  };

  $http(req)
    .success(function(response) {
      callbackFunc(response, "success");
    })
    .error(function(response) {
      console.log("Error Received");
      callbackFunc(response, "error");
    });
};

在控制器中:

$scope.Login = function() {

  AuthenticationService.authorize($scope.LoginRequest, function(response, responseCode) {
    if (responseCode === "success") {

      alert("Authentication Success");
    } else {
      alert("Authentication Failed");
    }
  });

};

1 个答案:

答案 0 :(得分:2)

AngularJS documentation for $http中所述,$ http调用返回带有错误方法的promise,该方法将状态的代码(编号)作为其中一个参数。您可以在那里检查401状态:

error(function(data, status, headers, config) {
    if(status === 401){
        // Add your code here
    }
  });