我想知道 Angular.js $http 拦截器是否在整个应用程序中共享。
假设我有一个myDependentApp模块,在许多应用程序之间共享。该模块配置了一些拦截器来控制 $http 请求/响应。我通过在应用程序引导程序中声明它来包含该模块:
angular.module('myApp', ['myDependentApp']);
我有应用程序模板:
<html ng-app="myApp">
myDependentApp拦截器会活跃吗myApp?
感谢帮助。
我想知道 Angular.js $http 拦截器是否在整个应用程序中共享。
假设我有一个myDependentApp模块,在许多应用程序之间共享。该模块配置了一些拦截器来控制 $http 请求/响应。我通过在应用程序引导程序中声明它来包含该模块:
angular.module('myApp', ['myDependentApp']);
我有应用程序模板:
<html ng-app="myApp">
myDependentApp拦截器会活跃吗myApp?
感谢帮助。
答案是肯定的,我在这里试过:
var dependentApp = angular.module('dependency',[]).config(['$httpProvider', function($httpProvider) {
$httpProvider.interceptors.push(function ($q) {
return {
'request': function (config) {
console.log('request intercept');
},
'response': function (response) {
console.log('response intercept');
}
};
});
}]);
var app = angular.module('myapp', ['dependency']);
app.controller('mycontroller', ['$scope', '$http', function ($scope, $http) {
$http.get('http://www.google.com');
}]);
我看到请求被拦截了。这是小提琴:http: //jsfiddle.net/6dbgo6pt/1/
出于全局错误处理、身份验证或任何类型的请求的同步或异步预处理或响应的后处理的目的,希望能够在请求被移交给服务器之前拦截请求并在响应被移交给之前拦截它们启动这些请求的应用程序代码。拦截器利用 Promise API 来满足同步和异步预处理的需求。
拦截器是通过将它们添加到 $httpProvider.interceptors 数组而向$httpProvider注册的服务工厂。工厂被调用并注入依赖项(如果指定)并返回拦截器。
使用 $httpProvider 更改 $http 服务的默认行为。