angular Uncaught ReferenceError: Service is not defined

ε祈祈猫儿з 提交于 2019-12-25 09:15:01

问题


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


回答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']);


来源:https://stackoverflow.com/questions/39440866/angular-uncaught-referenceerror-service-is-not-defined

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!