Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

ng中的provider写法 #21

Open
hjzheng opened this issue Jul 26, 2016 · 0 comments
Open

ng中的provider写法 #21

hjzheng opened this issue Jul 26, 2016 · 0 comments

Comments

@hjzheng
Copy link
Member

hjzheng commented Jul 26, 2016

最近,在项目中遇到需要在 config 阶段中注入一些service的情况,然而 factory,service 还有 value 是不能在 config 中注入的,先看一个清单:

服务/阶段 provider factory service value constant
config阶段 Yes No No No Yes
run 阶段 Yes Yes Yes Yes Yes

注意,provider 在config阶段,注入的时候需要加上 provider 后缀,可以调用非 $get 返回的方法
在 run 阶段注入的时候,无需加 provider 后缀,只能调用 $get 返回的方法

关于服务之间的关系: 大家可以参考官方文档给出的说明

provider(name, provider) - registers a service provider with the $injector
constant(name, obj) - registers a value/object that can be accessed by providers and services.
value(name, obj) - registers a value/object that can only be accessed by services, not providers.
factory(name, fn) - registers a service factory function that will be wrapped in a service provider object, whose $get property will contain the given factory function.
service(name, Fn) - registers a constructor function that will be wrapped in a service provider object, whose $get property will instantiate a new object using the given constructor function.
decorator(name, decorFn) - registers a decorator function that will be able to modify or replace the implementation of another service.

我们来举例说明 provider 的强大:

(function() {
    angular.module('app').provider('message', message);

    function message() {
        var level = 'log';
        // 该方法可以在 config 阶段使用
        this.setLevel = function(level) {
            level = level;
        };
        // 该方法返回的对象方法可以在 run 阶段使用
        this.$get = message;

        function message() {
            return {
                log: function() {
                    level ===  'log' ? console.log(arguments) : angular.noop() ;
                },
                error: function() {
                    level ===  'error' ? console.error(arguments) : angular.noop() ;
                },
                warn: function() {
                    level ===  'warn' ? console.warn(arguments) : angular.noop() ;
                }
            };
        };
    }
})();
// 注意注入的时候,加上Provider后缀
angular.module('app').config(function(messageProvider) {
     messageProvider.setLevel('error');
});
//注入的时候,无需加后缀
angular.module('app').controller('MainCtrl', function(message) {
     message.error('just a test');
});

参考资料: AngularJS Guide

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant