2017-02-17 32 views
-1

我正在使用Typescript在Angular 2中開發應用程序,並遇到問題。我具有獲取問題的陣列看起來像這樣按自定義對象數組中的屬性查找條目

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']), 

然後我有一個按鈕,允許用戶編輯的問題(所有數據包括ID)的服務。我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在這裏是不確定的,我不知道如何去它。

問題基本上圍繞發現問題數組中的權項其中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);