我正在使用 angularjs,加载和注册控制器,服务和工厂延迟加载。
我的配置文件类似于 用于注册和正常工作的 Dave's Answer 。
现在我想创建一个包含工厂定义的单独文件,该文件被延迟加载并用作拦截器。出于同样的目的,我在配置文件中创建了 app.interceptor 函数,该函数的定义为,
$httpProvider.interceptors.push('MyService');
但只要发送 ajax 请求,它就不会调用。知道为什么不起作用例如:myapp.config.js
var app = angular.module('app', [])
app.config(
function($controllerProvider, $provide, $compileProvider) {
// Since the "shorthand" methods for component
// definitions are no longer valid, we can just
// override them to use the providers for post-
// bootstrap loading.
console.log("Config method executed.");
// Let's keep the older references.
app._controller = app.controller;
app._service = app.service;
app._factory = app.factory;
app._value = app.value;
app._directive = app.directive;
app.controller = function(name, constructor) {
console.log("controller...");
console.log(name);
console.dir(constructor);
$controllerProvider.register(name, constructor);
return (this);
};
// Provider-based service.
app.service = function(name, constructor) {
$provide.service(name, constructor);
return (this);
};
// Provider-based factory.
app.factory = function(name, factory) {
$provide.factory(name, factory);
return (this);
};
// Provider-based value.
app.value = function(name, value) {
$provide.value(name, value);
return (this);
};
// Provider-based directive.
app.directive = function(name, factory) {
$compileProvider.directive(name, factory);
return (this);
};
app.interceptor = function(name) {
console.log("interceptor ----" + name)
$httpProvider.interceptors.push(name);
};
});
我的工厂.js
var app = angular.module('app');
app.interceptor('myfactory');
app.factory('myfactory', ['$q', '$location',function ($q, $location) {
return {
// optional method
request: function(config) {
// do something on success
console.log("request config");
console.log(config);
return config;
},
// optional method
requestError: function(rejection) {
// do something on error
console.log("requestError");
console.log(rejection);
return $q.reject(rejection);
},
// optional method
response: function(response) {
// do something on success
console.log("response response");
console.log(response);
return response;
},
// optional method
responseError: function(rejection) {
// do something on error
console.log("responseError");
console.log(rejection);
return $q.reject(rejection);
}
}
}]);