每當您向Web API發送HTTP請求時,都可以使用Angular攔截器將令牌放在請求標頭上。在這裏,我選擇演示承載認證。就像這樣:
appName.config(["$httpProvider", ($httpProvider: ng.IHttpProvider) => {
$httpProvider.interceptors.push(<any>["$q", "$location",
($q: ng.IQService, $location: ng.ILocationService) => {
return {
// config is the request data, including all its properties
'request': (config) => {
// Intercepting only the API requests
if (config.url.indexOf(apiServerUrl) >= 0) {
// Getting the token from local storage for example
var token = localStorage.getItem("token");
// Placing the token in the right header
if (token)
config.headers["Authorization"] = "Bearer " + token;
}
return config;
}
}
}
]);
}]);
謝謝,但我嘗試這種方法,攔截器不處理瀏覽器的請求只$ $。 –
我已更新問題 –