【问题标题】:AngularJS Provider doesn't accept ES6 function declaration [duplicate]AngularJS Provider 不接受 ES6 函数声明 [重复]
【发布时间】:2017-11-15 21:27:45
【问题描述】:

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

angular.js:63 Uncaught Error: [$injector:modulerr] 无法实例化模块应用程序,原因是: 错误:[$injector:pget] Provider 'books' 必须定义 $get 工厂方法。

这是我在这段代码中编写提供者对象的时候。

(() => {
    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 = () => { ... } 哪里一样?为什么会抛出这个错误?

【问题讨论】:

  • 箭头函数不是构造函数。当它被调用时,它永远不会让它的this 成为一个新的“实例”。
  • 不,它们不是一回事。查看副本。

标签: javascript angularjs ecmascript-6 function-expression


【解决方案1】:

箭头函数没有自己的“this”,而是使用周围代码的“this”。您必须使用传统函数。

this.$get = function() {

你可以在这里查看更深入的解释:

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

【讨论】:

  • 所以本质上,我是在global 对象上创建一个方法,而不是provider?这就是为什么我收到Provider 'books' must define $get factory method.
猜你喜欢
  • 2019-06-08
  • 1970-01-01
  • 2021-06-29
  • 1970-01-01
  • 2013-03-05
  • 1970-01-01
  • 2018-09-27
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多