Angular JS:在app.js

时间:2016-03-22 21:50:17

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

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

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

我真的相信这不是正确的方法,但它似乎很简单,我唯一缺少的就是注入帐户服务。

1 个答案:

答案 0 :(得分:2)

考虑这个模块,其中包含一个使用隐式DI的帐户:

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