分享Angular http interceptors 攔截器使用(推薦)
AngularJS 簡介
AngularJS 是一個 JavaScript 框架。它可通過 <script> 標簽添加到 HTML 頁面。
AngularJS 通過 指令 擴展了 HTML,且通過 表達式 綁定數(shù)據(jù)到 HTML。
攔截器
在開始創(chuàng)建攔截器之前,一定要了解 $q和延期承諾api
出于全局錯誤處理,身份驗證或請求的任何同步或異步預處理或響應的后處理目的,希望能夠在將請求移交給服務器之前攔截請求,并在將請求移交給服務器之前將響應攔截發(fā)起這些請求的應用程序代碼-攔截器利用promise api滿足同步和異步預處理的需求。
攔截器是$httpProvider通過將它們添加到$httpProvider.interceptors數(shù)組而向其注冊的服務工廠。調(diào)用工廠并注入依賴項(如果指定),并返回攔截器。
有兩種攔截器(和兩種拒絕攔截器):
- request:攔截器通過http config對象調(diào)用。該函數(shù)可以自由修改config對象或創(chuàng)建新對象。函數(shù)需要config直接返回對象,或者包含config或新config對象的Promise。
- requestError:當先前的攔截器拋出錯誤或被拒絕解決時,攔截器將被調(diào)用。
- response:攔截器通過http response對象調(diào)用。該函數(shù)可以自由修改response對象或創(chuàng)建新對象。函數(shù)需要response直接返回對象,或者作為包含response或新response對象的承諾。
- responseError:當先前的攔截器拋出錯誤或被拒絕解決時,攔截器將被調(diào)用。
// register the interceptor as a service
$provide.factory('myHttpInterceptor', function($q, dependency1, dependency2) {
return {
// optional method
'request': function(config) {
// do something on success
return config;
},
// optional method
'requestError': function(rejection) {
// do something on error
if (canRecover(rejection)) {
return responseOrNewPromise
}
return $q.reject(rejection);
},
// optional method
'response': function(response) {
// do something on success
return response;
},
// optional method
'responseError': function(rejection) {
// do something on error
if (canRecover(rejection)) {
return responseOrNewPromise
}
return $q.reject(rejection);
}
};
});
$httpProvider.interceptors.push('myHttpInterceptor');
// alternatively, register the interceptor via an anonymous factory
$httpProvider.interceptors.push(function($q, dependency1, dependency2) {
return {
'request': function(config) {
// same as above
},
'response': function(response) {
// same as above
}
};
});
此處有一個坑,在push時,提示未定義攔截器,因為$httpProvider在config 攔截器時,攔截器service 還不能找到,
可以將攔截器service 定義在config依賴的模塊中使用。
以上內(nèi)容是小編給大家分享Angular http interceptors 攔截器使用,希望對大家有所幫助!
相關文章
使用Angular 6創(chuàng)建各種動畫效果的方法
Angular能夠讓我們創(chuàng)建出具有原生表現(xiàn)效果的動畫。我們將通過本文學習到如何使用Angular 6來創(chuàng)建各種動畫效果。在此,我們將使用Visual Studio Code來進行示例演示。感興趣的朋友跟隨小編一起看看吧2018-10-10
Angularjs Ng_repeat中實現(xiàn)復選框選中并顯示不同的樣式方法
今天小編就為大家分享一篇Angularjs Ng_repeat中實現(xiàn)復選框選中并顯示不同的樣式方法,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2018-09-09
Angular 4根據(jù)組件名稱動態(tài)創(chuàng)建出組件的方法教程
組件是我們在學習angular中必不可少的一部分,下面這篇文章主要給大家介紹了關于Angular 4如何根據(jù)組件名稱動態(tài)創(chuàng)建出組件的相關資料,文中通過圖文與示例代碼介紹的非常詳細,需要的朋友可以參考借鑒,下面來一起看看吧。2017-11-11

