欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

分享Angular http interceptors 攔截器使用(推薦)

 更新時(shí)間:2019年11月10日 07:52:53   作者:erming  
AngularJS 是一個(gè) JavaScript 框架。它可通過 <script> 標(biāo)簽添加到 HTML 頁(yè)面。這篇文章主要介紹了分享Angular http interceptors 攔截器使用(推薦),需要的朋友可以參考下

AngularJS 簡(jiǎn)介

AngularJS 是一個(gè) JavaScript 框架。它可通過 <script> 標(biāo)簽添加到 HTML 頁(yè)面。

AngularJS 通過 指令 擴(kuò)展了 HTML,且通過 表達(dá)式 綁定數(shù)據(jù)到 HTML。

攔截器

在開始創(chuàng)建攔截器之前,一定要了解 $q和延期承諾api

出于全局錯(cuò)誤處理,身份驗(yàn)證或請(qǐng)求的任何同步或異步預(yù)處理或響應(yīng)的后處理目的,希望能夠在將請(qǐng)求移交給服務(wù)器之前攔截請(qǐng)求,并在將請(qǐng)求移交給服務(wù)器之前將響應(yīng)攔截發(fā)起這些請(qǐng)求的應(yīng)用程序代碼-攔截器利用promise api滿足同步和異步預(yù)處理的需求。

攔截器是$httpProvider通過將它們添加到$httpProvider.interceptors數(shù)組而向其注冊(cè)的服務(wù)工廠。調(diào)用工廠并注入依賴項(xiàng)(如果指定),并返回?cái)r截器。

有兩種攔截器(和兩種拒絕攔截器):

  • request:攔截器通過http config對(duì)象調(diào)用。該函數(shù)可以自由修改config對(duì)象或創(chuàng)建新對(duì)象。函數(shù)需要config直接返回對(duì)象,或者包含config或新config對(duì)象的Promise。
  • requestError:當(dāng)先前的攔截器拋出錯(cuò)誤或被拒絕解決時(shí),攔截器將被調(diào)用。
  • response:攔截器通過http response對(duì)象調(diào)用。該函數(shù)可以自由修改response對(duì)象或創(chuàng)建新對(duì)象。函數(shù)需要response直接返回對(duì)象,或者作為包含response或新response對(duì)象的承諾。
  • responseError:當(dāng)先前的攔截器拋出錯(cuò)誤或被拒絕解決時(shí),攔截器將被調(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
  }
 };
});

此處有一個(gè)坑,在push時(shí),提示未定義攔截器,因?yàn)?httpProvider在config 攔截器時(shí),攔截器service 還不能找到,

可以將攔截器service 定義在config依賴的模塊中使用。

以上內(nèi)容是小編給大家分享Angular http interceptors 攔截器使用,希望對(duì)大家有所幫助!

相關(guān)文章

最新評(píng)論