javascript - Angular 未捕获引用错误: Service is not defined

标签 javascript jquery angularjs angular-services

我有以下组件,我试图在其中注入(inject)服务:

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

当我运行这个时,我收到错误:

Uncaught ReferenceError: authenticationService is not defined

当我将“authenticationService”放入“”中时,出现错误:

Error [$injector:unpr] authtenticationService

最佳答案

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

将其更改为:

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

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

另外请务必为每个组件调用 angular.module 一次:

app.module.js

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

电话列表.module.js

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

关于javascript - Angular 未捕获引用错误: Service is not defined,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39440866/

相关文章:

javascript - Promise 是单播还是广播?

jquery - AngularJS + jQuery Flot + 使用 http.get 从 Controller 加载数据

javascript - 在 blur/focus 事件中,如果下一个焦点在同一个父元素中,你如何才能让 blur 不触发?

javascript - 如何使用异步模块在nodejs中实现回滚?

IE8 中的 jquery 错误 : 'Object' doesn't support this property or method

jquery - 如何使用 jQuery .each() 查找 child 的 child ?

jquery - 是否可以更改 JQuery 的 JQueryUI 自动完成生成的 Url?

node.js - 在 POST 上获取 ng-model 值到 Express.js 端点

angularjs - 添加没有值的属性

javascript - 如何从 jQuery 包装集中删除后代元素?