所以我有两个不同的html页面,两个不同的ng-app和两个控制器。我正在尝试在控制器和不同模块之间共享数据。

下面是应用程序的基本结构

index.html
-indexController.js
login.html
-loginController.js

sharedService.js

angular.module('sharedService', []).service('SharedService', function() {

var SharedService;

SharedService = (function() {

    function SharedService() {
        console.log('initializing');
    }

    var _data;
    SharedService.prototype.setData = function( data) {
        _data = data;
        /* method code... */
    };
    SharedService.prototype.getData = function( ) {
        return _data ;
    };
    return SharedService;

})();

if (typeof(window.angularSharedService) === 'undefined' || window.angularSharedService === null) {
    window.angularSharedService = new SharedService();
}
return window.angularSharedService;});


 angular.module("loginApp", ['sharedService'])
controller("loginCtrl",[
    'SharedService', function(SharedService){
    SharedService.setData(data);
    }

  angular.module("mainApp", ['sharedService'])
controller("someCtrl",[
    'SharedService', function(SharedService){
    console.log(SharedService.getData());
    }


事情是因为应用程序不同,所以我引用了

<script src="sharedService.js"></script>


服务被初始化两次。当我从loginApp设置数据时设置了数据,但是当我从mainApp查询数据时,它检索了未定义的值,我怀疑这是因为该服务再次被初始化并且是sharedService的另一个实例

最佳答案

您是正确的,该服务不会在不同html页面上的两个有角度的应用程序之间共享。您需要将要共享的数据持久保存在内存之外的其他位置,例如localStorage或远程服务器。 https://developer.mozilla.org/en-US/docs/Web/API/Storage/LocalStorage

10-04 21:49
查看更多