2017-02-17 5 views
-1

私は、Typescriptを使用してAngular 2でアプリケーションを開発していますが、問題があります。私はその後、私は質問(IDを含むすべてのデータ)を編集するためにユーザを可能にするボタンを持っています カスタムオブジェクト配列のプロパティによるエントリの検索

このような
export class Question { 

    constructor(public id: number, 
       public question_text: string, 
       public answers: string[], 
       public user_answer: string = "none") // default to none, update on user input 

    {} 
} 

private questions: Question[] = [ 
    new Question(0, 
    'How often did you eat a portion of vegetables??', 
    ['Answer A','Answer B', 'Answer C', 'Answer D', 'Answer E', 'Answer F']), 
    new Question(1, 
    'How often did you eat a portion of fruit?', 
    ['Answer A','Answer B', 'Answer C', 'Answer D', 'Answer E', 'Answer F']), 

を探して質問の配列を取得したサービスを持っています。私updateQuestionは次のようになります。私は本当に非常に最初のタスクに苦しんでいます

updateQuestion(questionId: number, newQuestion: Question) { 
    //Find question in array 
    //Delete this entry 
    //Add new question to array 

}

:配列内の質問を見つけます。私はいくつかの組み合わせを試しました

this.questions.find(question => questionId == id) 

しかし、私はそこに定義されていないと私はそれに到達する方法がわかりません。

問題は、基本的には、idは= questionId

すべてのヘルプははるかに高く評価される質問配列の右の項目を見つけるの周りを公転します!

+0

オーケーいますが、プロジェクト内の任意の場所にこの 'id'変数を設定しなかった私はあることを私の質問モデルを変更しましたか? –

+1

これは 'this.questions.find(question => questionId == question.id)' – Jag

+0

'Question'の外観はどうですか?ジャグはおそらく正しいでしょう。 – Cerbrus

答えて

0

問題は質問モデルで問題になりました。

export class Question { 

public _id: number; 
public _question_text: string; 
public _answers: string[]; 
public _user_answer: string; 

constructor(public id: number, 
      public question_text: string, 
      public answers: string[], 
      public user_answer: string = "none") // default to none, update on user input 

{ 
    this._id = id; 
    this._question_text = question_text; 
    this._answers = answers; 
    this._user_answer = user_answer; 
} 
} 

そして私のサービス:

updateQuestion(questionId: number, newQuestion: Question) { 
    const questionIndex = this.questions.findIndex(x => x._id == questionId); 
関連する問題