首页 > 解决方案 > 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 中,现在我想我需要采取不同的方法,目前正在测试一个类似于我在评论中留下的链接的解决方案。dashboardmyWidgetmyWidget

标签: angularjs

解决方案


好的,我很确定如果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();
}

推荐阅读