我使用本教程創建延遲加載: http://ify.io/lazy-loading-in-angularjs/AngularJS身份驗證服務在不同的文件
本教程進行身份驗證: https://coderwall.com/p/f6brkg
我想保存的身份驗證服務在不同的文件,說AuthenticationService.js
並注入它作爲依賴到我的app.js
。但是,app.js必須被引導,並且在我可以使用服務的define(['app'], function(){ ... }
之前返回。
我該如何做到這一點?
我至今:
app.js
define(
[
'app/scripts/routes',
'app/scripts/services/dependencyResolverFor',
'app/scripts/services/AuthenticationService',
'uiRouter'
],
function(config, dependencyResolverFor, AuthenticationService)
{
var app = angular.module('app', ['ngRoute','ui.router']);
console.log(AuthenticationService);
// Register all providers. We can now lazy load files as needed.
// Provide dependencies through the routes.js
app.config([
'$routeProvider',
'$locationProvider',
'$controllerProvider',
'$compileProvider',
'$filterProvider',
'$provide',
'$stateProvider',
function($routeProvider, $locationProvider, $controllerProvider, $compileProvider, $filterProvider, $provide, $stateProvider) {
app.controller = $controllerProvider.register;
app.directive = $compileProvider.directive;
app.filter = $filterProvider.register;
app.factory = $provide.factory;
app.service = $provide.service;
$locationProvider.html5Mode(false);
if(config.routes !== undefined) {
angular.forEach(config.routes, function(route, path) {
// Routing happens here
});
}
}
]);
// Check User
app.run(['$rootScope', '$state', function($rootScope, $state) {
$rootScope.$on("$stateChangeStart", function(event, currentRoute, prevRoute){
// Authenticate here and have access to the service
});
}]);
return app;
});
AuthenticationService.js(希望它是這樣目前,這是行不通的,因爲它說app
沒有定義,因爲它還沒有在app.js內返回
define(['app'], function(app)
{
app.service('AuthenticationService', function(){
var isLogged = false;
var user = 'guest';
var username = '';
this.login = function() { isLogged = true; };
this.checkLogin = function() { return isLogged; };
});
});