Search code examples
angularjsrequirejsamdangular-servicesangular-amd

Angular service injection using RequireJS


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


Solution

  • 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