2017-06-20 16 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; 
    } 
} 

が、私はそれを見つけるように見えることはできません。あらかじめありがとうございます!あなたは、このようなコードを変更した場合、それはあなたが変数の道を宣言することはできませんので、それはです

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

}

答えて

0

[OK]をする必要がありますので、クラス変数として変数デモを宣言する必要が

+0

これを行うと、コンストラクタの外側にある "var demos"の行を取り除くことはできますか? – WubbaLubbaDubbDubb

+0

別のクラスからgetDemosメソッドをログに記録するようコンソールに指示すると、 "undefined"が返されます。 – WubbaLubbaDubbDubb

+0

はい、コンストラクタまたは関数のいずれかのクラスでのみ変数を定義できるため、コンストラクタの外にある任意のvarデモを取り除くことができます。あなたの他の問題については、私はそれを見ることができるようにコードのサンプルを提供することができます。お願いします。 – ckruszynsky

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のクラスでスコープが動作するために発生します。

関連する問題