我們所有的內容頁面都有一個特定的標題X-Foo
。當ng-view
的內容發生變化時,我們希望在不同的元素中顯示新頁面的X-Foo
標題。如果內容發生變化,我們如何獲得這個值?在ng視圖更改時獲取標題
編輯:由於這顯然不清楚,標題預計在響應,而不是請求。
我們所有的內容頁面都有一個特定的標題X-Foo
。當ng-view
的內容發生變化時,我們希望在不同的元素中顯示新頁面的X-Foo
標題。如果內容發生變化,我們如何獲得這個值?在ng視圖更改時獲取標題
編輯:由於這顯然不清楚,標題預計在響應,而不是請求。
你可以通過$ http訪問控制器中的頭文件嗎?我沒有任何改變頭文件可用來測試。
controller('SampleCtrl', function($http, $scope) {
// Add headers from $http
$scope.http = $http.defaults.headers.common;
});
另外,如果不工作,你可能想看看使用http interceptors。
.config(function($routeProvider, $locationProvider, $httpProvider) {
$httpProvider.interceptors.push(function($q) {
return {
'response': function(response) {
// do something on success
console.log(response);
return response;
}
};
});
}
您可以使用httpInterceptor來做到這一點。 HTTP攔截器是在一個地方定義如何請求或響應使用$ http服務
app.config(function ($httpProvider) {
$httpProvider.interceptors.push('httpInterceptor');
}).factory('httpInterceptor', function (liveInterviewConfiguration) {
return {
request : function (request) {
console.info("Your request headers are");
console.info(request.headers);
return request;
},
requestError : function (error) {
return error;
},
response : function (response) {
return response;
},
responseError : function (error) {
return error;
}
};
});
當內容發生變化時,或者當路由改變所有的HTTP調用處理行爲的好辦法? 'ngView'有一個'$ viewContentLoaded'事件,你可以掛鉤。或者,如果您想在路由更改時進行連接,則會出現'$ routeChangeSuccess'事件。 – Ankh
@Ankh任何一個都沒問題。但是,我認爲,在路由發生變化的時候,新數據還沒有到來,所以沒有任何響應來獲取頭文件。 – user1207177