Angular JS:在 app.js 内注入服务
Angular JS: Inject service within app.js
我希望用户不要访问某些页面,至少他们之前已经登录过。我目前正在使用这个:
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
我真的相信这不是正确的方法,但它看起来很简单,我唯一缺少的是帐户服务注入。
考虑这个模块,它包含一个使用隐式 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
我希望用户不要访问某些页面,至少他们之前已经登录过。我目前正在使用这个:
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
我真的相信这不是正确的方法,但它看起来很简单,我唯一缺少的是帐户服务注入。
考虑这个模块,它包含一个使用隐式 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