这是我的角色代码中的一个正常的ES5功能:
app.run(function($templateCache){ $templateCache.put('/some','thing') });
我想把它转换成ES6的箭头功能
app.run($templateCache => $templateCache.put('/some','thing'));
但它给出错误
Uncaught Error: [$injector:unpr] Unknown provider: '/some'Provider <- '/some' http://errors.angularjs.org/1.4.6/$injector/unpr?p0='%2Fsome'Provider%20%3C-%20'%2Fsome' REGEX_STRING_REGEXP @ angular.js:68 (anonymous function) @ angular.js:4287 getService @ angular.js:4435 (anonymous function) @ angular.js:4292 getService @ angular.js:4435 invoke @ angular.js:4467 (anonymous function) @ angular.js:4297 forEach @ angular.js:336 createInjector @ angular.js:4297 doBootstrap @ angular.js:1657 bootstrap @ angular.js:1678 angularInit @ angular.js:1572 (anonymous function) @ angular.js:28821 trigger @ angular.js:3022 eventHandler @ angular.js:3296
ES6箭头功能是否与Angular不兼容?
编辑:我以为也许Angular不能推断名称$templateCache,所以无法注入它,但后来我登录到控制台,它确实显示它:
app.run($templateCache=>console.log($templateCache)); // => // Object {} // destroy: function() // get: function(key) // info: function() // put: function(key,value) // remove: function(key) // removeAll: function() // __proto__: Object
解决方法
正确.
Your version of AngularJS is not compatible with arrow functions that make use of $injector.
这主要是因为AngularJS 1.4.6使用(Function).toString,它不是以函数开始的(对于箭头函数,至少在Firefox中:
>var a = () => 5 function a() >a.toString() "() => 5" // not "function a() {return 5;}"
AngularJS支持从1.5.0 onwards的箭头符号.