factory、service、provider

作者: Nickyzhang | 来源:发表于2017-12-03 12:05 被阅读20次

    我们先通过一段代码来认识一下factoryserviceprovider

    var myApp = angular.module('myApp', []);
    /*
     * Factory
     */
    myApp.factory('Factory', function() {
        return {
            sayHello: function() {
                return "Hello, 张先生";
            }
        };
    });
    /*
     * Service
     */
    myApp.service('Service', function() {
        this.sayHello = function() {
            return "Hello, 张先生";
        };
    });
    /*
     * Provider
     */   
    myApp.provider('Provider', function() {
        this.name = '先生';
        this.$get = function() {
            var name = this.name;
            return {
                sayHello: function() {
                    return "Hello, " + name;
                }
            }
        };
    
        this.setName = function(name) {
            this.name = name;
        };
    });
    /*
     * config provider
     */        
    myApp.config(function(myProvider){
        myProvider.setName('张先生');
    });
    /*
     * 方法调用
     */
    function MyCtrl($scope, Provider, Factory, Service) {
        $scope.hellos = [
            Provider.sayHello(),
            Factory.sayHello(),
            Service.sayHello()];
    }
    
    factory: factory是以个可注入的function。当使用factory来创建服务的时候,相当于新创建了一个对象,然后在这个对象上新添属性,最后返回这个对象。
    service: service是一个可注入的构造函数。service是单例模式的。当使用service创建服务的时候,相当于使用new关键词进行了实例化。因此,你只需要在this上添加属性和方法,服务就会自动的返回this
    provider是一个可配置的factoryprovider是唯一一种可以创建用来注入到config()函数的服务的方式。想在你的服务启动之前,进行一些模块化的配置的话,就使用provider

    相关文章

      网友评论

        本文标题:factory、service、provider

        本文链接:https://www.haomeiwen.com/subject/irsabxtx.html