我从调试中了解到,在next()函数中未定义q。如何在数组中访问“id”以将值从组件(single.Value)推送到本地存储?非常感谢您提供的任何帮助!
<ion-navbar color="primary">
<ion-title>Quiz</ion-title>
<ion-buttons start>
<button ion-button icon-left (click)="prev()"><ion-icon name="arrow-back"></ion-icon> Prev</button>
</ion-buttons>
<ion-buttons end>
<button ion-button icon-right (click)="next(q)">Next<ion-icon name="arrow-forward"></ion-icon></button>
</ion-buttons>
</ion-navbar>
</ion-header>
<ion-content padding>
<ion-slides #Quiz>
<ion-slide *ngFor="let q of questions">
{{q.question}}
<range [single]="single"></range>
<progress-bar [progress]="loadProgress"></progress-bar>
</ion-slide>
</ion-slides>
</ion-content>
Typescript file:
export class QuizPage {
public RangeComponent;
public ProgressBar;
single = {
Value: 2
};
questions = [
{id: "programming", question: 'Which programming language do you prefer?'}
constructor(public navCtrl: NavController, public storage: Storage, public rangeComponent: RangeComponent, public progressBar: ProgressBarComponent) {
this.randomizeAnswers(this.questions);
this.setData();
this.getData();
}
randomizeAnswers(questions: any[]): any[] {
for (let i = this.questions.length - 1; i > 0; i--) {
let j = Math.floor(Math.random() * (i + 1));
let temp = this.questions[i];
this.questions[i] = this.questions[j];
this.questions[j] = temp;
}
return this.questions;
}
setData() {
this.storage.set('QuestionData', this.questions);
}
getData() {
this.storage.get('QuestionData').then((data) => {
console.log(data);
});
}
//slides
@ViewChild('Quiz') Quiz: any;
next(q) {
// console.log('single.Value is next');
console.log(this.single.Value);
this.saveToArray(q);
this.single.Value = 2; // Reset value to middle after every question
this.Quiz.slideNext();
this.progressBar.addProgress();
}
saveToArray(q) {
if (q.id == "programming") {
this.storage.set('programming', this.single.Value);
this.storage.get('programming').then((data2) => {
console.log("data logged.");
})
}
答案 0 :(得分:0)
q
在next()
函数中未定义,因为您在*ngFor
之外使用它。
您可以使用this.Quiz.getActiveIndex()
获取滑块的当前位置,然后直接从问题数组中获取ID,而不是将q传递到下一个函数中:
this.questions[this.Quiz.getActiveIndex()].id // check if the slide index starts at 0 or 1