2016-08-20 74 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; 
    } 
    }; 
}); 

在服务层,忽略验证这个头进行登录。