2017-07-24 67 views
0

即時消息得到上述錯誤消息,但不明白爲什麼一切都被定義,據我所知。TypeError:無法讀取未定義的屬性'問題'

繼承人我的html:

顯然,1號線

<div *ngIf="pager.index < quiz.questions.length"> 
    <h5 class="flow-text"><span [innerHTML]="quiz.questions[pager.index].text"></span></h5> 
    <br> 
    <div class="row text-left"> 
    <div class="col s12 m12" *ngFor="let answer of quiz.questions[pager.index].answers"> 
     <div class="answer"> 
     <input type="checkbox" [checked]="answer.selected" (change)="onSelect(answer);"/><label class="black-text flow-text"> {{answer.text}} </label> 
     </div> 
    </div> 
    </div> 
    <footer class="row"> 
    <div class="col s6 m6"></div> 
    <div class="col s6 m6"> 
     <div *ngIf="pager.index < quiz.questions.length - 1"> 
     <button id="nextButton" class="btn-flat black-text right flow-text" (click)="goTo(pager.index + 1);">Next</button> 
     </div> 
     <div *ngIf="pager.index == quiz.questions.length - 1"> 
     <button id="nextButton" class="btn-flat black-text right flow-text" (click)="goTo(pager.index + 1);">Finish</button> 
     </div> 
    </div> 
    </footer> 
</div> 

<div *ngIf="pager.index == quiz.questions.length"> 
    {{ selections }} 
</div> 

這裏發生錯誤是component.ts

import { Component, OnInit, EventEmitter } from '@angular/core'; 
import { QuizService } from '../services/quiz.service'; 
import { Answer, Question, Quiz } from '../models/index'; 
import {MaterializeAction} from "angular2-materialize"; 

@Component({ 
    selector: 'app-quiz', 
    templateUrl: './quiz.component.html', 
    styleUrls: ['./quiz.component.sass'], 
    providers: [QuizService] 
}) 
export class QuizComponent implements OnInit { 

    quiz: Quiz; 
    pager = { 
    index: 0, 
    size: 1, 
    count: 1 
    }; 
    selections: [string] 

    constructor(private quizService: QuizService) { } 

    ngOnInit() { 
    this.loadQuiz() 
    } 

    loadQuiz() { 

    this.quizService.get().subscribe(res => { 
     this.quiz = new Quiz(res); 
     this.pager.count = this.quiz.questions.length; 
    }); 
    } 

    goTo(index: number) { 
    if (index >= 0) { 
    this.pager.index = index; 
    } 
} 

onSelect(answer: Answer) { 
    if (answer.selected = true) { 
    this.selections.splice(this.selections.indexOf(answer.text), 1); 
    } else { 
    this.selections.push(answer.text); 
    } 
    answer.selected = !answer.selected 
} 
} 

我不明白爲什麼它作爲儘管錯誤發生編譯代碼工程並運行,除了我在另一個問題中提到的複選框外。

+0

測驗似乎沒有規定使用安全導航操作。 – robbannn

+0

[Observable type error:無法讀取未定義的屬性]的可能重複(https://stackoverflow.com/questions/34734671/observable-type-error-cannot-read-property-of-undefined) – Alex

回答

3

你應該在這種情況下

*ngIf="pager.index < quiz?.questions?.length" 

而且

*ngIf="pager.index == quiz?.questions?.length" 
+0

非常感謝你,當堆棧讓我接受答案時 – Wazza

0

看來quiz變量是undefined,定義它像這樣quiz: Quiz={}

相關問題