$window对象在其他模块中不可用

$window object is not available in other modules

本文关键字:模块 其他 window 对象      更新时间:2023-09-26

我为AngularJS应用程序创建了两个单独的模块。在第一个模块中,一旦我登录,我将登录信息和 API 密钥存储在 $window 对象中。

$window.sessionStorage["apiKey"] = apiKey;
$window.sessionStorage["profile"] = profile;

但是,我无法访问第二个模块中的窗口对象。

我的问题:
我可以使用任何工厂服务从其他模块访问窗口对象吗?
或者,如何在对象中保留$window属性?

您应该为此目的使用服务

创造

var myService = function ($http) { // injecting $http just for the sake of it
    var service = {};
    service.name = "My Service";
    return service;
};

添加到模块

app.service('myService', ['$http', myService]);

注入控制器

app.controller('MyController', ['$scope', 'myService', function ($scope, myService) {
    $scope.serviceName = myService.name;
}]);