0

I have the following component in which I am trying to inject a service:

angular.
  module('phoneList').
  component('phoneList', {
    templateUrl: '/static/common/angular/phone-list/phone-list.template.html',
    controller: ['$http', 'authenticationService',
      function PhoneListController($http, authenticationService) {
        var self = this;


          authenticationService.authenticate().then(function(){
                console.log('it worked!!!!!!!!');
                }); 

      }
    ]
  });

The service looks like this:

angular.module('authentication').factory('authenticationService', function($http, $se){
    function authenticate(){

        $http.post('/o/token/', data, config)
              .success(function (data, status, headers, config) {
                  console.log('auth service: '+data['access_token']);
                  $sessionStorage.access_token = data['access_token'];
              });
    }    
    function getToken(){
        return $sessionStorage.access_token;
    }
    return {
        authenticate:authenticate,
        getToken:getToken
    };
});

My phone-list.module.js looks like this:

angular.module('phonecatApp', [
  'phoneList',
  'authentication',
]);

angular.module('phoneList', ['authentication']);

When I run this i get the error:

Uncaught ReferenceError: authenticationService is not defined

When I put 'authenticationService' in '', I get the error:

Error [$injector:unpr] authtenticationService

Atma
  • 29,141
  • 56
  • 198
  • 299
  • @A1rPun I tried that and I get the same error. – Atma Sep 11 '16 at 21:53
  • You are defining `angular.module('phonecatApp')` twice which implies you want to create the module twice which is not possible. There is also an error in your error `authtenticationService` (maybe typo?). – A1rPun Sep 11 '16 at 22:02

1 Answers1

1

It seems the service isn't properly injected into the PhoneListController.

Change it to:

controller: ['$http', 'authenticationService',
  function PhoneListController($http, authenticationService) {
...

The strings in the array are just to keep the injected dependency references minification safe. The service still needs to be added as a function argument.

Also be sure to call angular.module once for each component:

app.module.js

angular.module('phonecatApp', [
  'ngRoute',
  'phoneList',
  'authentication',
]);

phone-list.module.js

angular.module('phoneList', ['authentication']);
Oberon
  • 200
  • 1
  • 9
  • Thanks for your help @Oberon. I get the error still: Error [$injector:unpr] authtenticationService. Do I need to add authtenticationService to my module dependency instead of 'authentication'? – Atma Sep 11 '16 at 22:20
  • 1
    I would follow @A1rPun suggestion and define the `phoneList` and `phonecatApp` modules only _once_. I'll edit my answer with a possible alternative. – Oberon Sep 11 '16 at 22:32
  • I did that as well and I get the same error. Thanks again for your help. – Atma Sep 11 '16 at 22:34