Are ES6 arrow functions incompatible with Angular?
Asked Answered
E

2

14

Here's a normal ES5 function in my Angular code which works:

app.run(function($templateCache){ $templateCache.put('/some','thing') });

I wanted to convert it to ES6 arrow function

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

but it gives the error

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

Are ES6 arrow functions incompatible with Angular?


EDIT: I thought perhaps Angular isn't able to infer the name $templateCache and so unable to inject it but then I logged it to console and it does show it correctly:

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
Exosmosis answered 21/9, 2015 at 16:20 Comment(2)
You shouldn't rely on the names of function's parameters, since it will stop working the moment you minify your code. Use something like ng-annotate.Misfire
The only difference seems to be that your function does return something. And the syntax of course.Fortunato
T
9

Correct. Your version of AngularJS is not compatible with arrow functions that make use of $injector.

This is mainly because AngularJS 1.4.6 makes use of (Function).toString, which does not start with function( for arrow functions, at least in Firefox:

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

AngularJS supports the arrow notation from 1.5.0 onwards.

Townspeople answered 21/9, 2015 at 16:38 Comment(1)
Your links show that basic support for arrow functions has existed since Angular 1.4.4. (Note the v1.4.4 tag on the commit in your second link.) I think the actual commit that bears on the OP's code is commit 03726f7f, which added support for arrow functions with an unparenthesized parameter for Angular 1.5.Bureaucratize
E
3

I tried another variation which worked: (x)=>… (instead of x=>…)

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

I guess it needs parentheses for some reason

Exosmosis answered 21/9, 2015 at 16:47 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.