WubbaLubbaDubbDubb WubbaLubbaDubbDubb - 1 month ago 7
AngularJS Question

Unexpected Token in Variable Declaration Javascript AngularJS

I'm trying to create a service in Angular, but my compiler (Gulp) seems to be having problems with the variable that I define in the beginning. The exact error is

Module build failed: SyntaxError: C:/*PATH*/src/app/components/demo.service.js: Unexpected token (8:8)
, and the code it's pointing at is this:
var demos = [new Demo("Example Demo", "<b>Example Demo</b>")];
with it pointing specifically at the "d" in the variable name. For context, here's the whole file:

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;
}
}


I'm sure this is a really stupid question and that the solution is really easy, but I just can't seem to find it. Thank you all in advance!

Answer Source

It's because you can't declare a variable the way you have declared demos in ES6.

Move this line :

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

into your constructor like this :

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

Then when you need to access demos just make sure you call this.demos. The error is because of the way scoping works in a class in ES6.