2014-04-01 35 views
1

我使用本教程創建延遲加載: 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; }; 
    }); 
}); 

回答

1

你可以把你的AuthenticationService放在一個單獨的角度模塊中,然後讓你的主應用依賴於子模塊。 AuthenticationService定義的模塊)。像...

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

則包括模塊:

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

編輯:你可以調用。名稱模塊對象(例如,一個越來越注入app.js),以獲得它的名字,所以你不必硬編碼'OtherModule'字符串作爲依賴,你可以做類似

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