当服务注入到其他地方时,角度提供程序配置重置
Angular provider configuration reset when service injected into somewhere else
这不是一个简单的描述,但基本上我有一个服务,它被设置为一个提供者,所以我可以配置它。它在我的项目中使用了一组API,最初是空的。各种配置块可以将API对象添加到数组中,这似乎是有效的。我每次都会console.log输出,并且数组正在增长。
然后,我将我的服务注入到其他东西中(在本例中是$http拦截器函数),并使用服务方法返回数组,但每次都会得到一个空数组。
我认为这是先运行所有配置块,然后拦截的$http调用就会发生,所以在拦截时数组应该已经充满了API。
不管怎样,这里有一些代码
angular.module('authModule').provider('authService', function(){
var _apis = [];
return({
addApi: addApi,
$get: instantiateAuth
});
function addApi(newApi){
_apis.push(newApi);
console.log("API added", _apis);
}
function instantiateAuth() {
return({
getApis: function(){
console.log("Getting APIs", _apis);
return _apis;
}
});
}
})
.config(function($httpProvider){
$httpProvider.interceptors.push(function($log, $rootScope, $q) {
return {
request: function(config) {
var injector = angular.injector(['ng', 'authModule']);
var authService = injector.get('authService');
console.log("apis", authService.getApis());
}
};
});
});
还有一个配置块示例
angular.module('myModule').config(function ($provide, authServiceProvider) {
authServiceProvider.addApi({
url: 'https://apiurl.com',
other: 'stuff'
});
authServiceProvider.addApi({
url: 'https://apiurl2.com',
other: 'stuff'
});
});
因此,每次在配置块中调用appApi方法时(这里调用两次),这一行都会输出数组console.log("API added",_apis);并且它在第一次调用之后正确地输出1个项目并且在第二次调用之后准确地输出2个项目。
当这个代码-authService.getApis()在第一次截获HTTP调用时触发时,它会将一个空数组记录到控制台。
任何帮助都将不胜感激。
编辑:
问题似乎是这条线
var注入器=角度注入器(['ng','authModule']);
每次发生这种情况时,我的提供者似乎都会被重置/重新创建,所以也许我误解了如何使用注射器。我最初只是以正常的方式在函数参数中注入我的authService,但我得到了一个循环依赖项(我的auth服务需要打开一个模式窗口,但angular ui模式依赖于http服务,我的http调用被拦截,以检查我的auth服务是否对用户进行了身份验证:()
是的,angular.injector(['ng', 'authModule'])
本质上创建了一个新的注入器实例(用外行的话说,是一个应用程序实例):
angular.injector(['authModule']) !== `angular.injector(['authModule'])
默认情况下加载ng
模块,无需显式指定。并且singleton服务是仅在同一注入器实例中的singleton:
injector.get('authService') === injector.get('authService');
但是
angular.injector(['authModule']).get('authService') !== `angular.injector(['authModule']).get('authService')
为了重用当前注入器实例(这在几乎所有情况下都是一种理想的行为),应该使用$injector
服务:
$httpProvider.interceptors.push(function($log, $rootScope, $q, $injector) {
return {
request: function(config) {
var authService = $injector.get('authService');
}
};
});
$injector.get
是解决循环依赖关系的已知且直接的解决方案。
- 如何在提供程序的配置中处理$rootScope
- 未从Selenium网络驱动程序中的配置文件接收到正确的值
- 当服务注入到其他地方时,角度提供程序配置重置
- webpack的库和客户端应用程序配置
- 需要.js 如何使用插件考虑填充程序配置
- 优化填充程序配置
- 在 ajax 响应中调用应用程序配置方法 - AngularJS
- 需要.js 事件发射器 2 的填充程序配置
- 删除 RequireJS 中未使用的填充程序配置
- 如何使用需要异步初始化的提供程序配置 angular
- 使用Google Analytics跟踪WebViews到应用程序配置文件中
- angular服务到应用程序配置中
- 单元测试提供程序配置中的$urlRouterProvider.otherwise
- 正在存储应用程序配置设置
- 如何测试AngularJS提供程序配置
- 单击应用程序通知后,如何重定向到我的应用程序配置文件页面
- 工作灯Facebook应用程序错误:“给定的URL是不允许的应用程序配置”
- Angular2如何从MVC传递应用程序配置
- ngRoute和Undercore.js需要js填充程序配置
- 移动应用程序-配置后端服务器地址