【问题标题】:How to inject services into a provider with angular 1.3如何使用 Angular 1.3 将服务注入提供程序
【发布时间】:2015-09-17 05:04:04
【问题描述】:

在我能找到的每条信息(包括角度文档)中,将服务注入提供者的方法是通过$get 方法:

var myApp = angular.module('myApp', []);

myApp.provider('helloWorld', function() {
    this.$get = function() {
        return {
            sayHello: function() {
                return "Hello, World!"
            }
        }
    };
});

function MyCtrl($scope, helloWorld) {    
    $scope.hellos = [helloWorld.sayHello()];
}

这将在 angular 1.2 及以下版本中完美运行:http://jsfiddle.net/1kjL3w13/

尽管切换到角度 1.3$get 函数完全中断。似乎从 $get 函数返回的任何内容都不再用于实例化提供程序,因此现在对于注入 f.e. 没有用。服务。

与上述示例相同,但使用 angular 1.3http://jsfiddle.net/duefnz47/

这正是 Angular 文档中提供的行为。所以要么文档是错误的,要么我完全误解了它。我真的不在乎 $get 方法是否像以前一样工作,我只需要能够可靠地将服务注入我的提供程序。

【问题讨论】:

  • 检查我的回答希望对你有帮助:)。
  • 服务、工厂、常量、值等不应该被注入到提供者中...而是在提供者公开的工厂中完成...
  • @deostroll 这是用于构建具有不同目的但可以在两者之间共享方法和内容的提供程序。想想一个“共享”的提供者,其基本功能被注入到许多其他提供者中。你的说法在那种情况下仍然成立吗?另外,需要注入的服务是 f.e. $window 服务,因为我确实需要在我的提供程序中访问它。它确实需要是一个提供者才能在config 方法中注入。
  • 这可以通过angular.injector() 完成。但不确定 1.3 支持...
  • 如果我在我的提供者中直接使用injector,它会被嘲笑吗?

标签: javascript angularjs dependency-injection angularjs-service angularjs-provider


【解决方案1】:

问题是您使用的全局控制器根据角度 1.3 无效

所以用

angular.module('myApp').controller('MyCtrl',function ($scope, helloWorld) {    
    $scope.hellos = [helloWorld.sayHello()];
});

这里更新fiddle

**

Migration Document official

** 希望对你有帮助:)

【讨论】:

  • 谢谢,这解决了这个问题,遗憾的是它是一个抽象,可能有点过于抽象,无法真正说明我的实际问题。由于复杂程度如此之多,很难想出一个简单的例子来展示这种行为。我的实际代码中仍然存在不使用全局控制器的问题。我会将其设置为已回答,因为您确实解决了这个特定问题。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-05-01
  • 2014-11-07
  • 2017-08-22
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多