角6:无法读取未定义的属性“长度”

时间:2018-10-24 14:03:44

标签: angular typescript input runtime-error parent-child

我有一个非常奇怪的问题。我正在使用@Input将数据从父级发送到子级组件,但出现此错误,但是当我尝试在ngOnInit中打印该值时,我得到了正确的值并且不是未定义的。 在父级和子级组件中打印数据时,已定义了父级中的数据,并且在控制台中获得了该值,但仍然收到该错误(即使我访问了数据)

这是错误的屏幕截图,以及我从console.log获取的值

enter image description here enter image description here

相关父html:

<quiz-course [quiz]="currentUnitQuiz"></quiz-course>

父项:

export class CoursePlayComponent implements OnInit {
  errorMessage: string;
  course: ICourse;
  courseId: number;

  // the current and prev quiz of this and prev unit (if there are)
  public currentUnitQuiz: IQuiz;
  public showQuiz: boolean;
  
  // .. more properties


  constructor(private courseService: CourseService,
      private route: ActivatedRoute,
      private router: Router,
      private userProgressService: UserProgressService) { }

  ngOnInit() {
      // save this course id from course-detail and get http request from the service
      this.courseId = JSON.parse(localStorage.getItem("courseId"));
      this.getCourse(this.courseId);
    }
    
  // Get course detail by id
  getCourse(id: number) {
      this.courseService.getCourse(id).subscribe(
          course => {
            this.course = course;
            
            // .. more code

            if (this.route.snapshot.firstChild.data.type == 'quiz') {
              this.getQuiz(this.currentUnitPos);
            }
          },
          error  => this.errorMessage = <any>error);
      }
      
      getQuiz(currentUnitPosition: number) {
      // .. more code
        this.showQuiz = true;
        this.currentUnitQuiz = this.course.units.find(u => u.position ===
        currentUnitPosition).quiz;
      }
 }

编辑:添加了更多代码,因此将很清楚。尝试访问长度时会遇到相同的错误,但是我也可以打印并获取数字,所以我不知道出了什么问题。

儿童ts:

export class CourseQuizComponent implements OnInit {

  @Input() quiz: IQuiz;
  
  // 1 = show the first page. 2 = show questions page. 0 = show neither
  public currentQuestion: IQuestion;
  public currentIndex: number;
  public currentUnit: number;
  public userAnswers: number[] = [];
  public correctAnswers: number;

  constructor(private courseService: CourseService,
      private route: ActivatedRoute,
      private router: Router,
      private fb: FormBuilder) { }

  ngOnInit() {
    console.log("length in child: ", this.quiz.questions.length); // **NOT** undefined
    this.restartQuiz();
  }
  
    restartQuiz() {
    this.currentUnit = +this.route.snapshot.paramMap.get('unitId');
    this.correctAnswers = 0;

    for(let i = 0; i < this.quiz.questions.length; i++) {
      this.userAnswers[i] = 0;
    }

    this.getCurrentQuestion(0);
  }

}

界面:

export interface IQuiz {
  id: number;
  name: number;
  unit_id: number;
  unit_position: number;
  questions: IQuestion[];
}

export interface IQuestion {
  id: number;
  name: string;
  quiz_id: number;
  position: number;
  question: string;
  answer1: string;
  answer2: string;
  answer3: string;
  answer4: string;
  correct: number;
  selected: number;
}

1 个答案:

答案 0 :(得分:1)

这是对孩子的输入,因此,为避免这些未定义的问题,我最好的选择是使用onchanges救生钩。

 import { OnChanges, SimpleChanges } from '@angular/core';

export class CourseQuizComponent implements OnInit, OnChanges {
  ngOnChanges(changes: SimpleChanges) {
   for (const prop of Object.keys(changes)) {
    const chng = changes[prop];
    if (prop === 'quiz') {
      this.quiz = chng.currentValue;
      // use this quiz variable in the restartQuiz() 
    }
  }
 }
 ngOnInit() {
   this.restartQuiz();
  }
}

尝试一下,让我知道是否可行。