Open Liudongge opened 7 years ago
service 通过构造函数的方式创建service,返回一个实例化对象
app.service("FooService",function() {
var self = this;
this.target = 'service';
this.sayHello = function() {
return "Hello " + self.target;
}
});
factory 把service的方法和数据放在一个对象里,并返回这个对象。
app.factory("FooService", function() {
return {
target: "factory",
sayHello: function() {
return "Hello " + this.target;
}
}
});
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.");
});
service factory provider