angular Uncaught ReferenceError: 服务未定义 [英] angular Uncaught ReferenceError: Service is not defined

查看:29
本文介绍了angular Uncaught ReferenceError: 服务未定义的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

      }
    ]
  });

服务如下所示:

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 看起来像这样:

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

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

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

运行时出现错误:

未捕获的引用错误:未定义 authenticationService

Uncaught ReferenceError: authenticationService is not defined

当我将 'authenticationService' 放入 '' 时,出现错误:

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

错误 [$injector:unpr] authtenticationService

Error [$injector:unpr] authtenticationService

推荐答案

服务似乎没有正确注入 PhoneListController.

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

改为:

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.

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

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

app.module.js

app.module.js

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

phone-list.module.js

phone-list.module.js

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

这篇关于angular Uncaught ReferenceError: 服务未定义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆