小編給大家分享一下Angular http interceptors攔截器怎么用,相信大部分人都還不怎么了解,因此分享這篇文章給大家參考一下,希望大家閱讀完這篇文章后大有收獲,下面讓我們一起去了解一下吧!

AngularJS 簡介
AngularJS 是一個 JavaScript 框架。它可通過 <script> 標簽添加到 HTML 頁面。
AngularJS 通過 指令 擴展了 HTML,且通過 表達式 綁定數據到 HTML。
攔截器
在開始創(chuàng)建攔截器之前,一定要了解 $q和延期承諾api
出于全局錯誤處理,身份驗證或請求的任何同步或異步預處理或響應的后處理目的,希望能夠在將請求移交給服務器之前攔截請求,并在將請求移交給服務器之前將響應攔截發(fā)起這些請求的應用程序代碼-攔截器利用promise api滿足同步和異步預處理的需求。
攔截器是$httpProvider通過將它們添加到$httpProvider.interceptors數組而向其注冊的服務工廠。調用工廠并注入依賴項(如果指定),并返回攔截器。
有兩種攔截器(和兩種拒絕攔截器):
request:攔截器通過http config對象調用。該函數可以自由修改config對象或創(chuàng)建新對象。函數需要config直接返回對象,或者包含config或新config對象的Promise。
requestError:當先前的攔截器拋出錯誤或被拒絕解決時,攔截器將被調用。
response:攔截器通過http response對象調用。該函數可以自由修改response對象或創(chuàng)建新對象。函數需要response直接返回對象,或者作為包含response或新response對象的承諾。
responseError:當先前的攔截器拋出錯誤或被拒絕解決時,攔截器將被調用。
// 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依賴的模塊中使用。
以上是“Angular http interceptors攔截器怎么用”這篇文章的所有內容,感謝各位的閱讀!相信大家都有了一定的了解,希望分享的內容對大家有所幫助,如果還想學習更多知識,歡迎關注創(chuàng)新互聯(lián)行業(yè)資訊頻道!
本文標題:Angularhttpinterceptors攔截器怎么用-創(chuàng)新互聯(lián)
網址分享:http://www.chinadenli.net/article46/decchg.html
成都網站建設公司_創(chuàng)新互聯(lián),為您提供營銷型網站建設、靜態(tài)網站、品牌網站制作、定制網站、網站維護、全網營銷推廣
聲明:本網站發(fā)布的內容(圖片、視頻和文字)以用戶投稿、用戶轉載內容為主,如果涉及侵權請盡快告知,我們將會在第一時間刪除。文章觀點不代表本網站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內容未經允許不得轉載,或轉載時需注明來源: 創(chuàng)新互聯(lián)