Angular使服务可以从任何地方访问

Angular making a service accessable from everywhere

本文关键字:方访问 访问 任何地 服务 Angular      更新时间:2023-09-26

我有一个服务,我正在使用它来检查我的用户是否被允许查看我的应用程序中的内容。

我是这样用的:

<tab ng-controller="LibraryRTLController" ng-if="authFactory.hasFeature('ReadyToLearn')">

然而,它似乎不能正常工作,因为我必须在每个控制器中初始化它,这似乎是多余的。

所以我的问题是:有没有办法在全球范围内使用服务?

请注意,由于我无法在这里开始解释的原因,我必须使用ng-if,因此属性指令对我没有帮助!

更新

所以我把它添加到我的运行函数中:

angular.module('app')
.run(function ($rootScope, AuthService, authFactory, $state) {
    $rootScope.authFactory = authFactory;
    $rootScope.$on('$stateChangeStart', function (event, next, toParams) {
        $state.newState = next;
        var authorizedRoles = next.data.authorizedRoles;
        if (!AuthService.isAuthorized(authorizedRoles)) {
            event.preventDefault();
            if (AuthService.isAuthenticated()) {
                // user is not allowed
            } else {
                // user is not logged in
                window.location.href = "http://" + window.location.hostname
            }
        }
    });
})

当调试时,我能够看到它实际上正确地设置了变量。

在我的服务中,我创建了一个简单的提醒功能:

function doesWork ()
{
    alert('true!');
}

现在回到我的html中,我有:

<tab ng-controller="LibraryRTLController" ng-init="authFactory.doesWork()">

但是没有任何结果?

有什么方法可以让我在全球范围内使用服务吗?

您可以简单地将服务公开为$rootScope属性,这样它就可以在每个模板中使用:

appModule.run(['$rootScope', 'authFactory', function($rootScope, authFactory) {
  $rootScope.authFactory = authFactory;
}]);

是的,您可以通过在注入依赖的主根文件中引用服务名称来全局访问服务

appModule.run(['$rootScope', 'authFactory', function($rootScope, authFactory) {
  $rootScope.authFactory = authFactory;
}]);