【问题标题】:Typescript/Angular - undefined property- how to access variable in arrayTypescript/Angular - 未定义的属性 - 如何访问数组中的变量
【发布时间】:2017-11-30 15:38:00
【问题描述】:

我从调试中了解到 q 在 next() 函数中是未定义的。如何访问我的数组中的“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.");
      })
    }

【问题讨论】:

    标签: angularjs typescript ionic2


    【解决方案1】:

    qnext() 函数中未定义,因为您在*ngFor 之外使用它。

    您可以使用this.Quiz.getActiveIndex() 获取滑块的当前位置,然后直接从问题数组中获取id,而不是将q 传递给您的下一个函数:

    this.questions[this.Quiz.getActiveIndex()].id // check if the slide index starts at 0 or 1
    

    【讨论】:

    • 感谢您的解释。这很有帮助。谢谢!
    猜你喜欢
    • 2016-05-08
    • 2019-09-12
    • 2012-06-15
    • 2020-03-20
    • 2012-12-29
    • 1970-01-01
    • 2018-01-14
    • 2019-01-30
    • 1970-01-01
    相关资源
    最近更新 更多