如何使用angular 1.3将服务注入提供商

How to inject services into a provider with angular 1.3

本文关键字:服务 注入 提供商 何使用 angular      更新时间:2023-09-26

在我能找到的每一条信息(包括角度文档)中,将服务注入提供者的方法是通过$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()];
}

这将在角度1.2及以下情况下完美工作:http://jsfiddle.net/1kjL3w13/

不过,切换到angular(角度)1.3$get功能完全中断。似乎从$get函数返回的任何内容都不再用于实例化提供者,因此现在对注入f.e.服务毫无用处。

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

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

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

所以使用

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

这里是更新的小提琴

**

移民文件官方

**希望它能有所帮助:)