AngularJS身份验证服务在另一个文件中

时间:2014-04-01 18:56:50

标签: angularjs authentication

我正在使用本教程创建延迟加载: http://ify.io/lazy-loading-in-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; };
    });
});

1 个答案:

答案 0 :(得分:1)

您可以将AuthenticationService放在单独的角度模块中,然后使主应用程序依赖于子模块(即定义AuthenticationService的模块)。类似......

angular.module('OtherModule', []).service('AuthenticationService', /* etc */);

然后包括模块:

var app = angular.module('app', ['ngRoute','ui.router', 'OtherModule']);

编辑:您可以在模块对象上调用.name(例如,注入app.js的那个)来获取它的名称,因此您不必将“OtherModule”字符串硬编码为依赖项,你可以做点什么

var app = angular.module('app', ['ngRoute','ui.router', InjectedModule.name]);