angular 中的不同类型的提供商配置

different kind of provider configurations in angular

从 Internet 上的不同资源学习 angular 真的很混乱。每个人都使用不同类型的模式来编写函数。请对此有所了解 .provider concept

我已经尝试 .provider 4 种不同的模式,并且都有效

模式 A : 使用 return

中的所有函数
app.provider('other', function() {
    name ="Default";
    return {
        $get: function () {
                return {
                    sayHello: function () { console.log('provider example say my name is :' + name )}
                }
        },
        setName: function (newName) {
            name = newName;
        }
    };
}); 

模式 B : 使用 this 并区别 $get 和其他方法

app.provider('other', function() {
    this.name ="Default";
    this.$get = function () {
        var name = this.name;
        return {
            sayHello: function () { console.log('provider example say my name is :' + name )}
        };
    };

    this.setName = function(name) {
        this.name = name;
    };
});

pattern C : 也发现在某处使用数组 [ ] 就在具有 return

的函数之前
this.$get = [function () {
        var name = this.name;
        return {
            sayHello: function () { console.log('provider example say my name is :' + name )}
        }
    }];

更新

Pattern D: with .factory 然后 functionNameProvider.$get.methodName() with .config

app.factory('alpha', function(){
        var c = ['Cadbury','Perk','Dairy Milk'];
        return {
            sayHello: function() { console.log('Hello, I am from Provider');},
            getAllData: function() { return c; }
        };
});

然后

app.config(['alphaProvider',function(alphaProvider) {
 console.group('Checking Factory Pattern');
 alphaProvider.$get().sayHello();
 var cdata = alphaProvider.$get().getAllData();
 console.log(cdata);
 console.groupEnd();
}]);

为此创建了一个 jsfiddle,请告诉我哪个是 correct/preferred 方式?

模式 A 和 B 都是创建 provider/service 的正确方法。

你传递给provider()方法的function是provider实例的构造函数。 Provider 实例只是一个具有 $get 方法的对象。关于如何实例化它,您有两种选择:

  • return 构造函数显式提供者实例(模式 A
  • 使用 this 语法和 return 构造函数中的任何内容( 模式 B)。在这种情况下,angular 将创建一个提供者实例作为一个新的 Object 和 运行 你的构造函数反对它(this 绑定到它)。

模式 CInline Array Annotation - 一种指定 component/function 依赖项的方法。该数组应包含依赖项的名称,后跟 function 您希望将它们注入的位置。可以与 A 和 B 方法一起使用。

更新

正如 @estus 所指出的,B 方法更有效,因为在 A 的情况下,新的 Object 也被创建但从未使用过。