话不多说,在我的controller中我打印一下我的service foo,当我没有在 config中使用 如下代码时
$provide.decorator('foo',function($delegate){ $delegate.greet = function(){ return "Hello, I am a new function of 'foo'"; } });
这个foo服务代码是;
appService.provider('foo', [function () { var thisIsPrivate = "Private"; return { setPrivate: function(newVal) { thisIsPrivate = newVal; }, $get: function() { function getPrivate() { return thisIsPrivate; } return { variable: "This is public", getPrivate: getPrivate }; } }; }])
当我不适用修饰器时,在controller中注入foo,是可以打印并且正常使用的,但是当我在 app.config中使用修饰器时,打印foo显示undefined,介是为嘛呢?
这个例子来自http://www.html-js.com/articl...
首先明确一点,config阶段 只能注入 provider 和 constant 而运行阶段 注入service, 也就是说
你在config阶段的写法应该如下:
app.config(function(fooProvider) { //注意是fooProvider 不是foo, 而且只能调用返回的非$get方法,不能使用 $get方法 返回的方法($get 返回的是 foo service 的方法)
fooProvider.setPrivate('New value from config');
});
具体参考我们团队内部总结: https://github.com/ShuyunXIAN...