Javascript 提供者 'xx' 必须从 AngularJs 中的 $get 工厂方法返回一个值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/27738903/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Provider 'xx' must return a value from $get factory method in AngularJs
提问by Reza
I have written an angularjsfactory as below
我写了一个angularjs工厂如下
module.factory('LogService', function () {
function log(msg) {
console.log("Rahkaran:" + new Date() + "::" + msg);
}
return
{
log: log
};
});
But I kept getting this error
但我一直收到这个错误
Provider 'LogService' must return a value from $get factory method
Provider 'LogService' must return a value from $get factory method
I googled about the error and I couldn't find any solution.
我在谷歌上搜索了错误,但找不到任何解决方案。
Coincidentally I changed the returnstatement to this
巧的是我把return语句改成了这个
return{
log: log
};
And error is gone!!
错误消失了!!
Is there any differences between having {in front of returnor at the next line?
{在前面return或在下一行之间有什么区别吗?
回答by Naeem Shaikh
This is called Automatic semicolon insertion
这称为自动分号插入
The return statement is affected by automatic semicolon insertion (ASI). There is no line terminator ;between the return keyword and the expression allowed.
return 语句受自动分号插入 (ASI) 影响。;return 关键字和允许的表达式之间没有行终止符。
return
a + b;
// is transformed by ASI into
return;
a + b;
So you must insert {in front of return and Not at the next line.
所以你必须{在 return 前面插入 而不是在下一行。
Reference:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/return
参考:https: //developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/return
回答by gringo_dave
In your case there will be always a non-undefined value returned. But in other cases the issue might be also that you do return null or undefined value from the factory.
在您的情况下,总会返回一个非未定义的值。但在其他情况下,问题也可能是您确实从工厂返回了 null 或 undefined 值。

