【问题标题】:Angular JS: Inject service within app.jsAngular JS:在 app.js 中注入服务
【发布时间】:2016-03-22 21:50:17
【问题描述】:

我希望用户不要访问某些页面,至少他们之前已经登录过。我目前正在使用这个:

app.run(function ($rootScope, $route, $location)
{
    var restrictedPages = 
            [   
                '/Survey/', '/Survey/Detalle', '/Survey/Accepted', '/Account/Profile',
                '/Auction/Detail', '/Survey/Accepted'
            ];

    $rootScope.$on('$locationChangeStart', function (ev, next, current)
    {
        var nextPath = $location.path();
        var nextRoute = $route.routes[nextPath];

        if(restrictedPages.indexOf(nextPath) !== -1)
        {
            $location.path('/home');
        }
    });
});

我的问题是我想在这段代码中注入我的 AccountService。我怎样才能做到这一点?因为加载顺序如下

  • app.js(此处提供的代码)

  • homeService.js

  • accountService.js

我真的认为这不是正确的方法,但它看起来很简单,我唯一缺少的就是帐户服务注入。

【问题讨论】:

  • AccountService 是如何定义的?
  • “注入”是什么意思?一个服务可以被注入到另一个服务中。但是不能注入“一段代码”。
  • 您是说您希望此运行块实例化并引用您的 AccountService?
  • @JBNizet 对不起,我所说的代码是指服务。

标签: angularjs angular-routing angular-services route-provider


【解决方案1】:

考虑这个模块,它包含一个使用隐式 DI 的 accountService:

angular.module('myApp', [])
.factory('accountService', function($rootScope) {
  // $rootScope is implicitly injected
})
.run(['$rootScope', '$route', '$location', 'accountService', function ($rootScope, $route, $location, accountService)
{
    var restrictedPages = 
            [   
                '/Survey/', '/Survey/Detalle', '/Survey/Accepted', '/Account/Profile',
                '/Auction/Detail', '/Survey/Accepted'
            ];

    $rootScope.$on('$locationChangeStart', function (ev, next, current)
    {
        var nextPath = $location.path();
        var nextRoute = $route.routes[nextPath];

        if(restrictedPages.indexOf(nextPath) !== -1 && !accountService.isLoggedIn())
        {
            $location.path('/home');
        }
    });
}]);

如果您需要更多文档:https://docs.angularjs.org/guide/di

【讨论】:

猜你喜欢
  • 2016-10-01
  • 1970-01-01
  • 2014-09-19
  • 2016-11-28
  • 1970-01-01
  • 2017-08-24
  • 2018-06-18
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多