2014-04-03 40 views
0

我使用AngularJS來構建單頁面應用程序。我希望代碼AnggularJS部分總是檢查身份驗證情況,每當有數據連接到服務器時總是發送頭部信息[X-Access-Token]。下面是我使用的代碼,但它可能有問題,因爲它不起作用。我必須用手將頭部X-Access-Token的數據添加到函數$ http get,post中。你有任何AngularJS的經驗,請幫助我!謝謝。Angular.js App的驗證API

app.factory('myHttpResponseInterceptor',['$q','$location',function($q,$location){ 
return function (promise) { 
    var success = function (response) { 
     return response; 
     console.log(response); 
    }; 

    var error = function (response) { 
     if (response.status == 401) { 
      //$state.go('signin'); 

     } 

     return $q.reject(response); 
    }; 

    return promise.then(success, error); 
}; 
}]); 

//Http Intercpetor to check auth failures for xhr requests 
app.config(['$httpProvider',function($httpProvider) { 
    $httpProvider.interceptors.push('myHttpResponseInterceptor'); 
}]); 


app.factory('api', function ($http, $cookieStore, flash, $state) { 
return { 
    init: function (token) { 
    $http.defaults.headers.common['X-Access-Token'] = token || $cookieStore.get('token'); 
    } 
}; 
}); 

app.run(function (api) { 
    api.init(); 
}); 

app.controller('adminProCatController', function($scope, $rootScope, flash, $state, $http, $cookieStore) { 

    $http.get('api/v1/categories?image_size=50x50', {headers: {'X-Access-Token': $cookieStore.get('token')}}).success(function(data) { 
     $scope.categories = data; 
    }); 
}); 

回答

1

識別身份驗證的用戶

可能有幾種方法來識別身份驗證的用戶;事實上可以設置一個全局變量,或者創建一個cookie ......但是我最喜歡的方式是使用AngularJS服務。 這種方法給了我幾個優點。 第一個優勢與每個AngularJS服務的真實性質密切相關;服務是單身人士,所以每個服務只有一個實例......這允許在不同的視圖,控制器,指令,過濾器和其他服務之間共享數據,而不需要過多地使用全局範圍。

您可以參考這個article

或者你尋找完整的解決方案 - git