Search code examples
javascriptangularjsecmascript-6function-expression

AngularJS Provider doesn't accept ES6 function declaration


I've been trying to rewrite some code of ours to comply with ES6 and have encountered the following issue.

angular.js:63 Uncaught Error: [$injector:modulerr] Failed to instantiate module app due to: Error: [$injector:pget] Provider 'books' must define $get factory method.

This is when I write the provider object in this code.

(() => {
    const app = angular.module('app', []);

    const books = () => { // Error is here
        let includeVersionInTitle = false;

        this.$get = () => {
            const appName = "Book Logger";
            const appDesc = "Track which books you read.";
            let version = "1.0";

            appName = (includeVersionInTitle) ? (appName += " " + version) : appName;

            return {
                appName: appName,
                appDesc: appDesc
            }
        };

        this.setIncludeVersionInTitle = (value) => {
            includeVersionInTitle = value;
        };
    };

    app.provider("books", [books]);
})();

When I change const books = () => { ... } to this, const books = function() { ... }. It'll work and not throw that error.

I thought that const a = function() { ... } and const a = () => { ... } where the same thing? Why does it throw this error out?


Solution

  • Arrow functions do not have their own "this", but use that of the surrounding code. You must use a traditional function.

    this.$get = function() {
    

    You can check out a deeper explanation here:

    https://derickbailey.com/2015/09/28/do-es6-arrow-functions-really-solve-this-in-javascript/