2017-02-17 33 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);