我正在使用Angular Material Stepper创建一个简单的True / False测试。测试结束时,您单击了提交按钮,该按钮调用了一项服务,该服务收集用户的答案并将其存储。
我的应用程序的结构如下:
这很简单。这是使用答案服务的问题步进器的打字稿代码
//Push results to service so other components can use it
gatherResults(){
this._answerService.setAnswers(
Object.values(this.firstFormGroup.value),
Object.values(this.secondFormGroup.value),
Object.values(this.thirdFormGroup.value),
Object.values(this.fourthFormGroup.value),
Object.values(this.fifthFormGroup.value),
Object.values(this.sixthFormGroup.value),
Object.values(this.seventhFormGroup.value),
Object.values(this.eigthFormGroup.value),
Object.values(this.ninthFormGroup.value),
Object.values(this.tenthFormGroup.value),
Object.values(this.eleventhFormGroup.value),
Object.values(this.twelthFormGroup.value)
);
let answers = this._answerService.retrieveAnswers();
console.log(answers);
}
这是答案服务的完整代码
export class AnswersService {
answers = {};
constructor() { }
setAnswers(a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12){
this.answers = {
answer1 : a1,
answer2: a2,
answer3: a3,
answer4: a4,
answer5: a5,
answer6: a6,
answer7: a7,
answer8: a8,
answer9: a9,
answer10: a10,
answer11: a11,
answer12: a12
}
}
retrieveAnswers(){
return this.answers;
}
}
所有这些代码都有效,但是,我有一个小问题。答案对象存在的格式。当我将答案对象记录在答案服务中时,它返回一个其中包含数组的对象。
我可以更改它,使其更像这样的对象
编辑
我曾尝试在Answers服务中调用setAnswers函数时删除Object.Values。这只是给了我价值的另一个对象。这是从前两个中删除它所得到的。
答案 0 :(得分:3)
Object.values(object)将对象转换为数组,因此,如果仅需要第一个值,则可以尝试此操作。
//Push results to service so other components can use it
gatherResults(){
this._answerService.setAnswers(
Object.values(this.firstFormGroup.value)[0],
Object.values(this.secondFormGroup.value)[0],
Object.values(this.thirdFormGroup.value)[0],
Object.values(this.fourthFormGroup.value)[0],
Object.values(this.fifthFormGroup.value)[0],
Object.values(this.sixthFormGroup.value)[0],
Object.values(this.seventhFormGroup.value)[0],
Object.values(this.eigthFormGroup.value)[0],
Object.values(this.ninthFormGroup.value)[0],
Object.values(this.tenthFormGroup.value)[0],
Object.values(this.eleventhFormGroup.value)[0],
Object.values(this.twelthFormGroup.value)[0]
);
let answers = this._answerService.retrieveAnswers();
console.log(answers);
}
如果要按名称命名所有值,可以尝试以下操作:
//Push results to service so other components can use it
gatherResults(){
this._answerService.setAnswers(
this.firstFormGroup.value.firstCtrl,
this.secondFormGroup.value.secondCtrl,
..
//And similarly for all forms
);
let answers = this._answerService.retrieveAnswers();
console.log(answers);