2016-08-20 78 views
0

我正在編寫一個使用ngRoute更改頁面的網站。 將出現,並且當它成功時,控制器會在下一步中更改請求的http標頭。 芽問題是,當我改變頭,頁面應該重新加載,如果不是,令牌不會被添加到頭。在angularjs中更改http請求標題而不刷新

控制器:

app.controller('catCtrl',['Api','$scope','$cookieStore','$rootScope',function (Api,$scope,$cookieStore,$rootScope) { 
$scope.Login = function(){ 
    Api.loginEmail($scope.log_email, $scope.pass, 'chrome', 'windows','').success(function(response){ 
     $cookieStore.put('Auth-Key', 'Token ' + response.token); 

     $scope.is_Loggedin = true; 
     $scope.showLoginWin(); 
    }).error(function(response){ 
     $scope.log_email = null; 
     $scope.pass = null; 
     $scope.error = response.error; 
    }); 
    }; 
} 

App.run:

app.run(['$cookieStore','$http',function($cookieStore, $http){ 

    $http.defaults.headers.common['Authorization'] = $cookieStore.get('Auth-Key'); 
}]); 

我怎樣才能改變頭無需重新加載頁面。

回答

1

因此您想在登錄後在進一步請求中添加令牌。

你可以嘗試角攔截器。這裏有幾個答案有關如何通過攔截器添加toke。

Interceptor Example 1

Interceptor example 2

示例代碼:

app.factory('httpRequestInterceptor', function() { 
    return { 
    request: function (config) {  
     config.headers['Authorization'] = $cookieStore.get('Auth-Key');  

     return config; 
    } 
    }; 
}); 

在服務層,忽略驗證這個頭進行登錄。