【问题标题】:Unexpected Token in Variable Declaration Javascript AngularJS变量声明Javascript AngularJS中的意外标记
【发布时间】:2017-06-20 16:13:31
【问题描述】:

我正在尝试在 Angular 中创建服务,但我的编译器 (Gulp) 似乎与我在开始时定义的变量有问题。确切的错误是Module build failed: SyntaxError: C:/*PATH*/src/app/components/demo.service.js: Unexpected token (8:8),它指向的代码是:var demos = [new Demo("Example Demo", "<b>Example Demo</b>")];,它专门指向变量名中的“d”。对于上下文,这是整个文件:

import { Demo } from './interfaces/demo';

export class DemosService {
    constructor() {
        'ngInject';
    }

    var demos = [new Demo("Example Demo", "<b>Example Demo</b>")];

    addDemo(name, html) {
        this.demos.push(new Demo(name, html));
    }

    removeDemo(name) {
        this.demos.splice(this.demos.indexOf(name), 1);
    }

    updateDemo(oldName, newName, html) {
        this.demos[this.demos.indexOf(oldName)].setName(newName);
        this.demos[this.demos.indexOf(oldName)].setHtml(html);
    }

    getDemoInfo(name) {
        return [this.demos[this.demos.indexOf(name)].getName(), this.demos[this.demos.indexOf(name)].getHtml()];
    }

    getDemos() {
        return this.demos;
    }
}

我确定这是一个非常愚蠢的问题,并且解决方案非常简单,但我似乎无法找到它。提前谢谢大家!

【问题讨论】:

    标签: javascript angularjs gulp


    【解决方案1】:

    这是因为你不能像在 ES6 中声明 demos 那样声明变量。

    移动这一行:

     var demos = [new Demo("Example Demo", "<b>Example Demo</b>")];
    

    像这样进入你的构造函数:

     constructor() {
            'ngInject';
          this.demos = [new Demo("Example Demo", "<b>Example Demo</b>")];
        }
    

    然后,当您需要访问演示时,请确保调用 this.demos。错误是因为 ES6 中的类中作用域的工作方式。

    【讨论】:

    • 这样做我可以摆脱构造函数之外的任何“var demos”行,对吗?
    • 我现在有另一个问题:告诉控制台记录另一个类的 getDemos 方法返回“未定义”。如果您愿意,我可以提供 Demo 课程
    • 是的,这样做你可以摆脱构造函数之外的任何 var 演示,因为变量只能在构造函数或函数中的类中定义。对于您的其他问题,您能否提供代码示例以便我查看;请。
    • 谢谢,不过我最终修复了它。感谢您的所有帮助!
    • @WubbaLubbaDubbDubb 很高兴你开始工作,没问题。
    【解决方案2】:

    你必须将 demos 变量声明为类变量,所以如果你像这样更改代码,应该没问题

    mport { Demo } from './interfaces/demo';
    
    export class DemosService {
    constructor() {
        'ngInject';
    }
    
    private demos:any = [new Demo("Example Demo", "<b>Example Demo</b>")];
    
    addDemo(name, html) {
        this.demos.push(new Demo(name, html));
    }
    
    removeDemo(name) {
        this.demos.splice(this.demos.indexOf(name), 1);
    }
    
    updateDemo(oldName, newName, html) {
        this.demos[this.demos.indexOf(oldName)].setName(newName);
        this.demos[this.demos.indexOf(oldName)].setHtml(html);
    }
    
    getDemoInfo(name) {
        return [this.demos[this.demos.indexOf(name)].getName(), this.demos[this.demos.indexOf(name)].getHtml()];
    }
    
    getDemos() {
        return this.demos;
    }
    

    }

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-04-16
      • 1970-01-01
      • 2013-06-14
      • 2020-06-04
      • 2013-09-11
      • 1970-01-01
      • 2022-07-05
      相关资源
      最近更新 更多