[英]Understanding provider in Angularjs
我对angularjs还是很陌生,我想了解一些基础知识。 谁能解释我为什么以下示例中未定义某些值。
(function () {
'use strict';
var app = angular.module('app', []);
app.constant('configuration', {
CONSTANT: "This is from constant",
});
app.provider('test',['configuration', function (configuration) {
this.testItem1 = configuration.CONSTANT + "+ TestItem1";
this.$get=['configuration', function(configuration){
return {
testItem2: configuration.CONSTANT + "+ TestItem2"
}
}];
}]);
app.config(['testProvider', function (tp) {
console.log("From app.config: " + tp.testItem1);
console.log("From app.config:" + tp.testItem2); //undefined
}
]);
app.run(['test', function(test){
console.log("From app.run:" + test.testItem1); //undefined
console.log("From app.run:" + test.testItem2);
}]);
})();
我也对生命周期或流程有疑问。 我假设这就是它的流动方式。 app.config-> DI测试提供程序-> DI配置常数-> app.run。 如果我错了,请纠正我。 谢谢。
Plunkr演示: http ://plnkr.co/edit/2TIqgxMxBJEPbnk2Wk6D?p=preview
提供者和服务之间有区别。
Provider是一个具有$get
方法的对象,即,当您使用时:
app.config(['testProvider', function (tp) {
console.log("From app.config: " + tp.testItem1);
console.log("From app.config:" + tp.testItem2); //undefined
}
]);
tp
是:
this.testItem1 = configuration.CONSTANT + "+ TestItem1";
this.$get=['configuration', function(configuration){
return {
testItem2: configuration.CONSTANT + "+ TestItem2"
}
}
另一方面,当您使用时:
app.run(['test', function(test){
console.log("From app.run:" + test.testItem1); //undefined
console.log("From app.run:" + test.testItem2);
}]);
tp
是:
{
testItem2: configuration.CONSTANT + "+ TestItem2"
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.