【问题标题】:Trouble with Angular Resource InjectionAngular 资源注入的问题
【发布时间】:2016-04-23 02:30:24
【问题描述】:

我正在开始使用 meanjs 堆栈,并且已经达到了一些我不了解正确 google 的头疼问题。

我有以下文件: **

(function () {
'use strict';

  angular
    .module('students')
    .controller('StudentsListController', StudentsListController);

  StudentsListController.$inject = ['StudentsService'];

  function StudentsListController(StudentsService) {
    var vm = this;

    vm.students = StudentsService.query();
  }
}());

使用此服务,我可以在 list-students 控制器中获取一组 Student 对象,接下来:

list-students.client.controller.js

(function () {
  'use strict';

  angular
    .module('students')
    .factory('StudentsService', StudentsService);

  StudentsService.$inject = ['$resource'];

  function StudentsService($resource) {
    return $resource('api/students/:studentId', {
      studentId: '@_id'
    }, {
      update: {
        method: 'PUT'
      }
    });
  }
}());

这按预期工作。 我不明白的是,为什么当我尝试在另一个控制器中使用相同的服务时,它似乎无法注入,给我留下一个未定义的 StudentsServices 变量。 什么给了?

students.client.controller.js

(function () {
'use strict';

  // Students controller
  angular
    .module('students')
    .controller('StudentsController', StudentsController);  

  StudentsController.$inject = ['$scope', '$state', 'Authentication',   'StudentsService'];

  function StudentsController ($scope, $state, Authentication, student, StudentsService) {
    var vm = this;

    vm.authentication = Authentication;
    vm.student = student;
    vm.students = StudentsService.query();
...
}());

【问题讨论】:

    标签: javascript angularjs


    【解决方案1】:

    你的注入是错误的。

    '$scope', '$state', 'Authentication',   'StudentsService'
    

    但你是在告诉控制器期待

    $scope, $state, Authentication, student, StudentsService
    

    【讨论】:

      【解决方案2】:

      我想通了,每 AngularJS: Factory is always undefined when injected in controller

      我的注入需要与传递给控制器​​函数的参数的顺序相同。

      啊哈!

      【讨论】:

        猜你喜欢
        • 2012-05-19
        • 1970-01-01
        • 2010-10-27
        • 1970-01-01
        • 2021-02-06
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-04-02
        相关资源
        最近更新 更多