2017-06-20 37 views
0

我正嘗試在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」。對於上下文,這裏是整個文件:變量聲明中的意外令牌Javascript AngularJS

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

我敢肯定,這是一個非常愚蠢的問題和解決的辦法是真的很容易,但我似乎無法找到它。謝謝大家!

回答

0

這是因爲你不能聲明一個變量的方式你已經在ES6中聲明瞭演示。

移動這一行:

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的一個類中作用域的方式。

+0

在這樣做,我可以擺脫構造函數外的任何「var demos」行,正確嗎? – WubbaLubbaDubbDubb

+0

我現在有另一個問題:告訴控制檯從另一個類中記錄getDemos方法返回「undefined」。我可以提供Demo類,如果你想 – WubbaLubbaDubbDubb

+0

是的,你可以在構造函數之外去除任何var演示,因爲變量只能在構造函數或函數的類中定義。對於您的其他問題,您可以提供代碼樣本,以便我可以看到它;請。 – ckruszynsky

0

您必須聲明爲類變量,變量的演示,所以如果你改變這樣的代碼,它應該是確定

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

}