在自定义对象数组

时间:2017-02-17 14:20:39

标签: javascript arrays angular typescript angular2-services

我正在使用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

任何帮助都将不胜感激!!

1 个答案:

答案 0 :(得分: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);