【问题标题】:Class constructor BaseService cannot be invoked without 'new'没有'new'就不能调用类构造函数BaseService
【发布时间】:2017-10-27 15:07:26
【问题描述】:

我正在尝试将 Angular js 服务用作 ES6 类。但出现错误。

没有'new'就不能调用类构造函数BaseService。

这是服务代码。

"use babel";

(function() {
  'use strict';

  class BaseService {
    constructor() {
      this.data = {
        items: []
      };
    }

    loadData() {
      this.data.items = ['one', 'two', 'three'];
    }
  }

  angular.module('app').service('BaseService',  BaseService);
}());

这是我正在尝试的链接。 https://embed.plnkr.co/D9MEJZe4pF6oztf7DP31/

【问题讨论】:

  • 你的问题是什么?
  • 我的问题是为什么我上面的代码给出了错误类构造函数 BaseService 不能在没有'new'的情况下被调用我包括索引.html 中的基本服务。请参阅embed.plnkr.co/D9MEJZe4pF6oztf7DP31 以获取不起作用的完整代码。感谢您的回复。

标签: javascript angularjs ecmascript-6


【解决方案1】:

// your Base Service class file
export default class BaseService {
    constructor() {
        this.data = {
            items: []
        };
    }
}

// your Angular service file
import BaseService from './base.service.js'; // relative path to BaseService file

export default class MyService extends BaseService {
    constructor() {
        super();
    }
}

// module definition file
import MyService from './my.service.js'; // relative path to MyService file
module.exports = angular.module('myMod',[])
.service('MyService', MyService);

【讨论】:

  • 感谢您的回复。此代码给出错误 Uncaught SyntaxError: Unexpected token import。我是 ES6 的新手。我希望我的服务充当类,以便我可以执行继承。
  • 这段代码绝对有效(我每天整天都在使用这种模式),但你仍然需要先用 Babel 编译它。
  • 除非您的“基础”服务本身也是一个真正的 Angular 服务,否则您不需要将其注册为 Angular 服务。它可以是您在注册的 Angular 服务中扩展的独立“类”。我将更新我的代码示例来说明。
【解决方案2】:

这是您使用的 AngularJS 版本 (1.5.0-rc.0) 中的一个问题。它无法正确构造一个类。升级到 1.5.0 或更高版本,错误就会消失。

【讨论】:

    猜你喜欢
    • 2017-09-29
    • 2018-09-19
    • 1970-01-01
    • 1970-01-01
    • 2018-11-12
    • 2019-04-21
    • 2021-05-17
    • 2021-12-27
    相关资源
    最近更新 更多