angularjs - AngularJS 共享服务不充当模块之间的单例
问题描述
我已经看到了这个问题的多种形式,但似乎无法为我的问题找到正确的答案。
以下问题是服务无法在其他模块/控制器之间共享数据。它不充当单例。意思是,如果我添加窗口dashboard
并调用,windowService.getWindows()
我将看到我添加的窗口。但是,如果我在myWidget
通过仪表板添加它们之后执行相同操作,反之亦然,则服务中的集合是空的,就好像其他模块/控制器没有添加任何东西一样。我在这里做错了什么?我希望服务保留一个单一的窗口集合,并且可以从我的任何其他模块访问。
模块 1
var dashboard = angular.module('dashboard', [windowServiceModule]);
dashboard.controller('DashboardController', function DashboardController(windowService) {...stuff});
模块 2
var myWidget = angular.module('myWidget', [windowServiceModule]);
myWidget.controller('MyWidgetController', function MyWidgetController(windowService) {...stuff});
服务
var windowServiceModule = angular.module('windowService', []);
windowServiceModule.service('windowService', function() {
var windows = [];
this.addWindow = function(win)
{
this.windows.push(win)
}
this.getWindows = function()
{
return this.windows;
}
});
编辑:在浏览其他答案时,我尝试了这个:Share a single service between multiple angular.js apps
我认为这暴露了问题的一部分。以上建议迭代$rootScope
集合,但在我的情况下,集合中只有一个,并且在and$rootScope
之间不一样。事实上,它在 iframe 中,现在我想我需要采取不同的方法,目前正在测试一个类似于我在评论中留下的链接的解决方案。dashboard
myWidget
myWidget
解决方案
好的,我很确定如果myWidget
没有在 iframe 中加载,我的初始代码会运行良好。我有一个仪表板可以打开嵌入或弹出的窗口,我想使用该服务来管理窗口并处理来回传递状态,因为弹出 iframe 需要重新加载页面。
无论如何,我现在在服务中有这样的东西并且它正在工作:
var windowServiceModule = angular.module('windowService', []);
windowServiceModule.service('windowService', function($window) {
...stuff
var parentScope = $window.parent.getScope();
...other stuff
之后,您可以使用 parentScope 访问父范围内的任何内容。我传入 angular $window
。
仅供参考,getScope()
已存在于父 JSP 文件中。看起来是这样的:
function getScope()
{
return angular.element($("#DashboardController")).scope();
}
推荐阅读
- c# - 如何在插入大型数据集后首先以编程方式重建代码中的所有索引(C# 和 EntityFrameworkCore)创建的 SQL Server 表
- c# - 让隐式派生类构造函数调用基类构造函数
- maven - 没有 kotlin-stdlib maven 依赖的 kotlin 数据类
- php - 试图在laravel中获取非对象的属性'expiry_date'
- javascript - 使用引导卡每 3 行循环一次
- c# - 用随机数填充数组,但 rand 方法的工作速度不够快?
- javascript - 从 Javascript 到 Python 代码的简单算法不会产生相同的结果
- java - 菜单显示但未调用 onCreateOptionsMenu()
- azure-devops - [[_TOC_]] 不再适用于 VSTS/Azure DevOps
- rest - Webhook 和 API(定义和差异)