3

I'm using AngularAMD + RequirsJS for a single page app and I'm having some issues when injecting a service in the app.js file.

Here the code:

login_service.js

define(['app'], function(app) {
'use strict';

    app.service('loginService', function($location, $state, Restangular) {

        return {

            login: function(data, scope) {},

            logout: function() {},

            isLogged: function() {}

        }

    });

});

app.js

define(['angularAMD', 'restangular', 'angular-ui-router'], function(angularAMD) {
'use strict';

    var app = angular.module('MyApp', ['restangular', 'ui.router', 'loginService']);

    app.run(function($rootScope, $state, $stateParams, $location, loginService) {

        console.log(loginService)

        /*
        Error: [$injector:modulerr] Failed to instantiate module MyApp due to: [$injector:modulerr] 
        Failed to instantiate module loginService due to:
        $injector:nomod] Module 'loginService' is not available! You either misspelled the module name or forgot to load it.
         */

    });

    app.config(function($stateProvider, $urlRouterProvider, $i18nextProvider, RestangularProvider) {

    });

});

I would liked to access the loginService in the run function but can't as I keep getting the "Failed to instantiate module MyApp" error message.

I've tried to load the login service file as follow:

define(['angularAMD', 'restangular', 'angular-ui-router', 'services/login_service'], function(angularAMD) {

});

But then I have another error stating that app is undefined in the Login Service.

Thank you very much for your helps.

David

JDL
  • 231
  • 4
  • 16

2 Answers2

0

It is happeing because 'loginService' is not a module it's a service and you cannot add 'loginService' (service) to the module you can only add only module to another module. you can do one thing :-

 var app = angular.module('loginService',[]);
app.service('loginService', function($location, $state, Restangular) {

        return {

            login: function(data, scope) {},

            logout: function() {},

            isLogged: function() {}

        }

    });

Ps:- I am not sure about this :-P

squiroid
  • 13,809
  • 6
  • 47
  • 67
0

The problem is caused by the fact that requireJS loads the files dynamically and this assures you that the files are already loaded before it runs the code.

You should do the following:

  1. Remove the ng-app from your html

  2. Use a manual bootstrapping:

        angular.element().ready(function(){
            angular.bootstrap(document,['MyApp']);
    
        });
    
Michael
  • 3,308
  • 5
  • 24
  • 36