当 $http returns 某些状态时定义默认操作

Define default action when $http returns certains status

是否可以在我的应用中为 $http 设置默认操作?

我的想法是,如果控制器中的任何 $http 调用,或者我的应用程序的服务会 return 405,我可以更改为状态 'login'

类似这样的东西(当然这根本行不通,但我想这说明了这个想法)

angular.module('app',[]).config(function($http){
    $http.error(function(error,state){
    if (state===405){
        do stuff
    }
);

你应该这样做:

$http({
  method: 'GET',
  url: '/someUrl'
}).then(function successCallback(response) {
  //Do whatever you want on success
}, function errorCallback(response) {
  if(response.status == 405) {
    //Go to login
  }
});

您可以使用拦截器来实现这一点。

// register the interceptor as a service
$provide.factory('myHttpInterceptor', function($q, dependency1, dependency2) {
  return {
// optional method
'request': function(config) {
  // do something on success
  return config;
},

// optional method
'requestError': function(rejection) {
  // do something on error
  if (canRecover(rejection)) {
    return responseOrNewPromise
  }
  return $q.reject(rejection);
},



// optional method
'response': function(response) {
  // do something on success
  return response;
},

// optional method
'responseError': function(rejection) {
  // do something on error
  if (canRecover(rejection)) {
    return responseOrNewPromise
  }
  return $q.reject(rejection);
}
};
});

$httpProvider.interceptors.push('myHttpInterceptor');


// alternatively, register the interceptor via an anonymous factory
$httpProvider.interceptors.push(function($q, dependency1, dependency2) {
return {
'request': function(config) {
   // same as above
},

'response': function(response) {
   // same as above
}
};
});

了解更多信息 here

以下代码可能对您有所帮助:

       $http.get("url")
       .success(function (data, status, headers, config) {
           $scope.content = data;
           if (data == '405') {
          $state.go('login', {id: the_necesarry_id});                

           }
           else   {window.alert(' ');}
       })
       .error(function (data, status, headers, config) {

        });

使用angularjs Interceptors

 // interceptors.js

    .factory('httpInterceptor', function ($q, $injector) {
        return {
       'requestError': function(rejection) {
                // do something on error
                if(rejection.status === 405){
                   $injector.get('$state').transitionTo('login');                    
                }
                return $q.reject(rejection);
           },
      'responseError': function(rejection) {
                // do something on error
                if(rejection.status === 405){
                     $injector.get('$state').transitionTo('login');                     
                }
                return $q.reject(rejection);
             }
         };
    });


    // app.js

    app.config( function ($httpProvider, $interpolateProvider, $routeProvider) {
        $httpProvider.interceptors.push('httpInterceptor');

        ...
    });