AngularJS Provider不接受ES6函数声明

时间:2017-11-15 21:27:45

标签: javascript angularjs ecmascript-6 function-expression

我一直在尝试重写我们的一些代码以符合ES6并遇到以下问题。

  

angular.js:63未捕获错误:[$ injector:modulerr]由于以下原因,无法实例化模块应用程序:   错误:[$ injector:pget]提供商'书籍'必须定义$ get factory方法。

这是我在此代码中编写提供程序对象的时候。

(() => {
    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]);
})();

当我将const books = () => { ... }更改为此const books = function() { ... }时。它会起作用而不会抛出那个错误。

我认为const a = function() { ... }const a = () => { ... }同样的事情?为什么会抛出这个错误?

1 个答案:

答案 0 :(得分:0)

箭头功能没有自己的"这个",但使用周围代码的功能。你必须使用传统的功能。

this.$get = function() {

您可以在此处查看更深入的解释:

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