Liudongge / JavaScript_Notes

learn and work by JS
0 stars 0 forks source link

Angular中service,factory和provider的关系 #5

Open Liudongge opened 7 years ago

Liudongge commented 7 years ago

service factory provider

Liudongge commented 7 years ago

service 通过构造函数的方式创建service,返回一个实例化对象

app.service("FooService",function() {
    var self = this;
    this.target = 'service';
    this.sayHello = function() {
        return "Hello " + self.target;
    }
});
Liudongge commented 7 years ago

factory 把service的方法和数据放在一个对象里,并返回这个对象。

app.factory("FooService", function() {
    return {
        target: "factory",
        sayHello: function() {
            return "Hello " + this.target;
        }
    }
});
Liudongge commented 7 years ago

provider 创建一个可以通过config配置的service,$get中返回的,就是factory中创建service的内容

app.provider("FooService", function() {
    this.comfigData = "Init data.";
    this.setConfigData = function(data) {
        if (data) {
            this.configData = data;
        }
    }
    this.$get = function() {
        var self = this;
        return {
            target: "provider",
            sayHello: function() {
                return self.configData + " Hello " + this.target;
            }
        }
    }
});
// 此处注入的是FooService的provider
app.config(function(FooServiceProvider) {
    fooServiceProvider.setConfigData("Config data.");
});