在我的角度應用程序中,我想覆蓋$ http。所以只要有$ http服務調用,它會在原始數據中附加一些默認數據併發送請求。同樣,當一個響應到來時,它會檢查一些特定的數據並重新格式化它,success()將得到修改後的響應。
我是Angularjs的新手。誰可以幫我這個事?
預先感謝您。
在我的角度應用程序中,我想覆蓋$ http。所以只要有$ http服務調用,它會在原始數據中附加一些默認數據併發送請求。同樣,當一個響應到來時,它會檢查一些特定的數據並重新格式化它,success()將得到修改後的響應。
我是Angularjs的新手。誰可以幫我這個事?
預先感謝您。
您可以使用下面的代碼。
//或者,通過匿名工廠註冊攔截
$httpProvider.interceptors.push(function($q, dependency1, dependency2) {
return {
'request': function(config) {
// do your stuff
return config;
},
'response': function(response) {
// do your stuff
return response;
}
};
});
你必須探索通過角度實現的$ http方法。你可以看到一個功能
function sendReq (config, reqData, reqHeaders)
在這裏,你可以改變reqData按您的要求。 現在類似的成功和完成功能,你可以使用你的代碼來處理數據,然後發送到回調。 否則,您也可以更改來自xhr請求的數據。 這個你會從函數createxhr()中得到的角度
看看$ http攔截器(https://docs.angularjs.org/api/ng/service/ $ http)。使用它們,您可以攔截請求和ajax請求的響應。
創建類似的服務:
module.factory('myHttpInterceptor', function($q, dependency1, dependency2) {
return {
'request': function(config) {
// do something pre-request, like inject Headers properties:
//config.headers['Authorization'] = '';
return config;
},
'requestError': function(rejection) {
//do something with the error
return $q.reject(rejection);
},
'response': function(response) {
// do something on success of request
return response;
},
'responseError': function(rejection) {
// do something on error like:
//if(response.status == 401){
// userUnauthorized();
//}
return $q.reject(rejection);
}
};
});
在你的應用程序配置,推動攔截器:
module.config(['$httpProvider', function($httpProvider) {
$httpProvider.interceptors.push('myInterceptor');
}]);
它看起來不錯。讓我試試看。謝謝!! – Alp
可以使用的$ HTTP攔截。閱讀關於這裏「http://www.webdeveasy.com/interceptors-in-angularjs-and-useful-examples/」 –
你到目前爲止嘗試過什麼?任何支持面向方面構造的庫都可以工作。你可以看看這個:https://github.com/mgechev/angular-aop –