【问题标题】:angular Uncaught ReferenceError: Service is not defined角度未捕获的ReferenceError:未定义服务
【发布时间】:2016-09-11 21:32:30
【问题描述】:

我尝试在以下组件中注入服务:

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

【问题讨论】:

  • @A1rPun 我试过了,我得到了同样的错误。
  • 您定义了两次angular.module('phonecatApp'),这意味着您想创建两次模块,这是不可能的。您的错误authtenticationService 中也有错误(可能是错字?)。

标签: javascript jquery angularjs angular-services


【解决方案1】:

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

改成:

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

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

也一定要为每个组件调用angular.module一次

app.module.js

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

电话列表.module.js

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

【讨论】:

  • 感谢您的帮助@Oberon。我仍然收到错误:错误 [$injector:unpr] authtenticationService。我是否需要将 authtenticationService 添加到我的模块依赖项而不是“身份验证”?
  • 我会遵循@A1rPun 的建议并只定义phoneListphonecatApp 模块一次。我会用一个可能的替代方案编辑我的答案。
  • 我也这样做了,但我得到了同样的错误。再次感谢您的帮助。
猜你喜欢
  • 2014-06-17
  • 1970-01-01
  • 1970-01-01
  • 2014-02-21
  • 1970-01-01
  • 2017-06-23
  • 1970-01-01
相关资源
最近更新 更多