I am migrating some code from Angular1 to Angular2 and having a few issues. I can open a json response, populate a template, and access data from template ng functions but have not been able to access the data directly from the component class. From what I have read and the error messages seen Angular2 http / observable does not seem to return a pure json object, so I suspect I need to remap it, but not sure how. I believe it should also be possible to drop back to promises using onPromise but have not managed to get that working. I have spent a lot of time googling for solutions, and have tried to implement most of them, but no luck. If anyone can advise on how to remap the response to a usable format or directly access data in the response it would be greatly appreciated.
Example http call from the service :-
getExam() {
return this._http.get('/json/exam.json')
.map(data => data.json());
}
Example subscribe :-
ngOnInit() {
this._examsService.getExam()
.subscribe(response => this.exam = response);
console.log(this.exam.length); //this fails
}
Example console log error :-
TypeError: Cannot read property 'length' of undefined in [null]
Example data structure (very simplified for testing) :-
{"title":"My Practice Exam",
"questions":[
{"question":"1+1 = ",
"answers":[
{"answer":"2","correct":"Y","selected":"N","iscorrect":""},
{"answer":"5","correct":"N","selected":"N","iscorrect":""}]},
{"question":"2+2 = ",
"answers":[
{"answer":"4","correct":"Y","selected":"N","iscorrect":""},
{"answer":"7","correct":"N","selected":"N","iscorrect":""}]},
{"question":"3+3 = ",
"answers":[
{"answer":"6","correct":"Y","selected":"N","iscorrect":""},
{"answer":"8","correct":"N","selected":"N","iscorrect":""}]}]}
In Angular1 I was able to directly access data from functions - e.g as follows, and would like to do similar in Angular2
if ($scope.myExams[0].questions[q].answers[a].correct == 'y') ...