簡體   English   中英

ES6箭頭功能是否與Angular不兼容?

[英]Are ES6 arrow functions incompatible with Angular?

這是我的Angular代碼中的普通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

正確。 您的AngularJS版本與使用$ injector的箭頭函數不兼容。

這主要是因為AngularJS 1.4.6使用了(Function).toString ,它不是以function(開頭的function(對於箭頭函數,至少在Firefox中:

>var a = () => 5
function a()
>a.toString()
"() => 5"  // not "function a() {return 5;}"

AngularJS支持從1.5.0開始的箭頭符號。

我嘗試了另一個有效的變體: (x)=>… (而不是x=>…

app.run(($templateCache) => $templateCache.put('/some','thing'));

我想由於某種原因它需要括號

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM