Angular注入了“false”,而不是我请求的服务



我有一个定义如下的控制器:

angular.module('myApp')
  .controller 'DetailController', ($rootScope, $scope, $routeParams, apiService) ->
    onStart = () ->
      getData()
      getOtherData()
    # a bunch of other functions defined here
    getData = ->
      apiService.get('/detail/' + $routeParams.id).then (result) ->
        $scope.data = result.data # really a little bit more involved :)
    onStart()

这是有效的。

现在,我想使用一些otherServicegetData()函数中做一件额外的事情。假设otherService被定义为

angular.module('myApp')
  .factory 'otherService', () ->
    doTheThing = -> console.log('did the thing!')
    {
      doTheThing
    }

(这适用于应用程序的其他部分)。

为了在我的控制器中使用这个,我这样做:

angular.module('myApp')
  .controller 'DetailController', ($rootScope, $scope, $routeParams, apiService, otherService) ->
    onStart = () ->
      getData()
      getOtherData()
    # a bunch of other functions defined here
    getData = ->
      apiService.get('/detail/' + $routeParams.id).then (result) ->
        $scope.data = result.data # really a little bit more involved :)
        otherService.doTheThing()
    onStart()

即在自变量列表的末尾添加一个自变量otherService,然后使用它

这给了我一个TypeError,因为doTheThing没有定义。调试时,我看到otherService包含值false,而不是我请求的服务。

为什么?

我不太喜欢Coffeescript,但当我使用Try Coffeescept转换代码时(http://coffeescript.org/),我得到了:

angular.module('myApp').factory('otherService', function() {
  var doTheThing;
  doTheThing = function() {
    return console.log('did the thing!');
  };
  return {
    doTheThing: doTheThing
  };
});
angular.module('myApp').controller('DetailController', function($rootScope, $scope, $routeParams, apiService, otherService) {
  var getData, onStart;
  onStart = function() {
    getData();
    return getOtherData();
  };
  getData = function() {
    return apiService.get('/detail/' + $routeParams.id).then(function(result) {
      $scope.data = result.data;
      return otherService.doTheThing();
    });
  };
  return onStart();
});

我不确定是否返回onStart,因为Controller应该是普通的构造函数,但没关系,我尝试过jsbin,并用$q.when删除未满足的依赖关系,它有效。

http://jsbin.com/cubekojuwu/edit?js,控制台,输出

关于工厂的主要内容是它应该返回对象,该对象应该放在DI容器中,并且您的代码看起来可以。所以我想你的问题是在运输我们在这里看不到的东西时。

你能提供完整的"不工作"的jsbin吗?您可以将已转换的代码放入其中。

最新更新