Angular JS:为什么 module.config 注入和控制器注入有区别? [英] Angular JS: why the difference between module.config injection and controller injection?

查看:25
本文介绍了Angular JS:为什么 module.config 注入和控制器注入有区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我在深入研究 AngularJS 代码中无法弄清楚的事情,也许您可​​以帮助解开这个谜.

This is something that I could not figure out from digging into the AngularJS code, maybe you can help solve the mystery.

为了展示它,我向 AngularJS 种子项目添加了一个服务:

To show it, I added a service to AngularJS seed project:

function MyServiceProvider() {
    console.log('its my service');
    this.providerMethod = providerMethod;

    function providerMethod() {
        console.log('its my service.providerMethod');
    }

    this.$get = $get;

    function $get() {
        var innerInjectable = {
             name: 'stam'
        };
        return innerInjectable;
    }
}

var serviceModule = angular.module('myApp.services', []).
    value('version', '0.1').
    provider('myservice',MyServiceProvider);

您可以看到此提供程序公开了 $get 和某个 'providerMethod'.

You can see that this provider exposes $get and a certain 'providerMethod'.

现在,对于注入用法:如果我们调用 config,我们可以注入整个类并访问外部"提供程序方法:

Now, for the injection usage: If we call config, we can inject the whole class and get access to the 'outer' provider method:

serviceModule.config(function(myserviceProvider) {
    console.log('myServiceProvider:',myserviceProvider);
    myserviceProvider.providerMethod();
});

但是当我们将其注入控制器时(注意 Provider-less 名称),只有 $get 返回值被暴露:

But when we inject this to a controller (note the Provider-less name), only the $get return value is exposed:

function MyCtrl1(myservice) {
    console.log('MyCtrl1.myservice =',myservice,myservice.name);
}
MyCtrl1.$inject = ['myservice'];

控制台输出如下:这是我的服务我的服务提供者:构造函数 {providerMethod: function, $get: function}它是我的 service.providerMethodMyCtrl1.myservice = Object {name: "stam"} stam

Console output follows as it should: its my service myServiceProvider: Constructor {providerMethod: function, $get: function} its my service.providerMethod MyCtrl1.myservice = Object {name: "stam"} stam

谁能解释一下区别?原因?非常感谢您的任何想法

Can any one explain the difference? The reason? many thanks for any thought

利奥

PS:我在 angular-ui new ui-router 中看到了这种技术(优秀的项目!).我需要访问外部提供程序类才能在 jasmine 和其他地方进行注入 - 无济于事

PS: I've seen this technique in angular-ui new ui-router (excellent project!). I need access to the outer provider class to do injection in jasmine and other places - to no avail

推荐答案

从 Angular 邮件列表中我得到了一个惊人的 线程 解释了服务、工厂和提供者以及它们的注入用法.我决定把它放在自己的问题这里

From the Angular mailing list I got an amazing thread that explains service vs factory vs provider and their injection usage. I decided to put it in its own question here

具体的答案是:这是设计使然,允许在配置时配置提供程序.

the specific answer is: it is so by design, to allow configuration of the provider at config time.

这篇关于Angular JS:为什么 module.config 注入和控制器注入有区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆