I have been trying to sort this out for a while now and could definitely use some help. I am trying to display the question I got from the server and stored locally. But When i try to display the question that i got it gives me the following error:
Cannot read property 'question' of undefined
Here's my HTML
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Questionnaire</title>
</head>
<body>
<div class="container" id="Question" align="center">
<h2 [innerHTML] = "q.question"></h2>
</div>
</body>
</html>
Here's typescript that is for sure returning values because i can log them and so I checked:
@Component({
selector: 'app-new-questionnaire',
templateUrl: './new-questionnaire.component.html',
styleUrls: ['./new-questionnaire.component.css'],
providers: [NewServerRequestsService]
})
export class NewQuestionnaireComponent implements OnInit {
q: any;
sub: any;
id: number;
cQuestion: number;
score: number;
qNumber: number;
constructor(private serverService: NewServerRequestsService, private
route: ActivatedRoute, private router: Router){}
static questionTime = performance.now();
onload()
{
console.log(NewQuestionnaireComponent.questionTime);
// this.ButtonClicks();
}
ngOnInit() {
this.sub = this.route.params.subscribe(params => {
// (+) converts string 'id' to a number
// fetch the file and get next Question
this.id = +params['id'];
if (localStorage.getItem('q') !== null) {
var data = JSON.parse(localStorage.getItem('q'))
this.qNumber = parseInt(localStorage.getItem('qNumber'))
this.q = data.results[this.id - 1]
} else {
this.serverService.getQuestion()
var data = JSON.parse(localStorage.getItem('q'))
this.qNumber = parseInt(localStorage.getItem('qNumber'))
this.q = data.results[this.id - 1]
}
});
}
}
}
Here's the service:
@Injectable()
export class NewServerRequestsService {
constructor(private http: Http) { }
getQuestion()
{
return this.http.get("https://opentdb.com/api.php?amount=30")
.map(res => res.json()).subscribe(
data => {
// shuffle questions
for (var i = 0; i < data.results.length - 1; i++) {
var j = i + Math.floor(Math.random() * (data.results.length -
i));
var temp = data.results[j];
data[j] = data.results[i];
data[j].incorrect_answers.push(data[j].correct_answer)
data[i] = temp;
}
localStorage.setItem("q", JSON.stringify(data))
localStorage.setItem("qNumber", JSON.stringify(data.length))
},
err => console.error(err)
)
}
}
Here's where the data gets fetched:
@Component({
selector: 'home',
templateUrl: 'home.component.html',
providers: [NewServerRequestsService]
})
export class HomeComponent implements OnInit, OnDestroy {
constructor(private QuizService: NewServerRequestsService, private route:
ActivatedRoute, private router: Router) {
}
ngOnInit() {
this.QuizService.getQuestion();
}
ngOnDestroy() { }
}