Handle redirects in angularjs $http

后端 未结 3 929
粉色の甜心
粉色の甜心 2020-12-05 18:43

I\'m using angularjs http service in my app, and I noticed this in the website:

If the AJAX call succeeds (the server sends back an HTTP code between

3条回答
  •  星月不相逢
    2020-12-05 18:59

    I think there is a better way than the http interceptor for login redirection because it parses the request response and if another page has the string requested, an error will occur.

    I suggest wrapping $http methods in your service and check if the user is logged before making the request:

    app.service('httpWrapper', ['$http','requestLogin',function($http,requestLogin){
      var httpWrapper = {};
    
      // You can add methods for put, post
      httpWrapper.get = function(url){
        // Before making the request, check with a request if the user is logged
        $http.get(urlLogged).success(function (auth) {
            if(!auth.logged){
                // Show login widget
                requestLogin.show();
            }
        }).error(function(){
    
        });        
        return $http.get(url);
      }
    
      return httpWrapper;
    }]);
    

    Then uses httpWrapper in place of $http in your other services:

    app.service('otherService', ['httpWrapper',function(httpWrapper){
      httpWrapper.get(url);
    }]);
    

    Here the service for requestLogin:

    app.service('requestLogin', ['$rootScope',function($rootScope){
      var requestLogin = {};
    
      $rootScope.showlogin = false;
    
      requestLogin.show = function(){
        $rootScope.showlogin = true;
      }
    
      requestLogin.hide = function(){
        $rootScope.showlogin = false;
      }    
      return requestLogin;
    }]);
    

    And then, in your view:

    Please log-in...

提交回复
热议问题