angular Uncaught ReferenceError:未定义服务

时间:2016-09-11 21:32:31

标签: javascript jquery angularjs angular-services

我有以下组件,我正在尝试注入服务:

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!!!!!!!!');
                }); 

      }
    ]
  });

服务如下:

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
    };
});

我的phone-list.module.js如下所示:

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

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

当我运行时,我得到错误:

  

未捕获的ReferenceError:未定义authenticationService

当我提出' authenticationService'在'',我收到错误:

  

错误[$ injector:unpr] authtenticationService

1 个答案:

答案 0 :(得分:1)

似乎服务没有正确地注入PhoneListController。

将其更改为:

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

数组中的字符串只是为了保持注入的依赖引用缩小安全。该服务仍然需要添加为函数参数。

还要确保为每个组件调用angular.module 一次

app.module.js

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

电话list.module.js

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