2014-10-20 10 views
0

我正在使用角的$ httpBackend模擬後端。

有沒有辦法攔截每個請求到$ httpBackend以驗證令牌?

現在,我可以在每個URL調用中都這樣做,就像波紋管一樣 - 但我想模擬一箇中間件,所以我不需要爲每個url請求都做這件事,例如我會有10個。

angular.module( '應用')。運行([ '$ httpBackend', 'MoviesDataModel',函數($ httpBackend,MoviesDataModel){

$httpBackend.whenPOST('/movies').respond(function(method, url, data, headers) { 

     // Check the X-AUTH-TOKEN value. 
     var authToken = headers['X-AUTH-TOKEN']; 

     // If we have a auth token 
     if (authToken === 'headervalue') { 
      // Check if the token is valid. 
      var params = angular.fromJson(data), 
       movie = MoviesDataModel.addOne(params), 
       movieId = movie.id; // get the id of the new resource to populate the Location field 
      return [201, movie, { Location: '/movies/' + movieId }]; 
     } else { 
      // 401 Unauthorize - The user is not logged in. 
      return [401, '', {}]; 
     } 
    }); 

    $httpBackend.whenGET(/\.html$/).passThrough(); 

}]); 

回答

0

可以使用decorator攔截所有的來電$httpBackend並做任何你想做的事

angular.module('http-app') 
.config(['$provide', 
    function($provide) { 

    $provide.decorator('$httpBackend', function($delegate) { 

     var interceptedCalls = [], 

     //Create a new function that will proxy calls to 
     // the $httpBackend service 
     newHttpBackend = function(method, url, post, callback, headers, 
            timeout, withCredentials, responseType) { 

      //Trivial example of tracking each call 
      // and a timestamp 
      interceptedCalls.push({ 
      method: method, 
      url: url, 
      timestamp: new Date() 
      }); 

      //Now call the original with all the arguments 
      return $delegate(method, url, post, callback, headers, 
          timeout, withCredentials, responseType); 

     }; 

     newHttpBackend.interceptedCalls = interceptedCalls; 

     //Return the proxy function 
     return newHttpBackend; 

    }); 
    } 
]); 
相關問題