I've encountered an issue while attempting to save JSON data from my API into an array of Model objects. Despite trying different approaches, the console always logs "undefined" when I try to print the array. This even happens with a simple array that should work fine. I'm quite new to Angular 2 and TypeScript, so any help on what might be missing in my code would be greatly appreciated.
results : Array<Recipes> = new Array(20);
sample = ['one','two','three'];
getResults(): Observable<Recipes[]>{
return this.http.get('<my perfectly functioning API endpoint here>')
.map(this.extractData)
.catch(this.handleErrorObservable);
}
private extractData(res: Response) {
let body = res.json();
console.log(this.sample); **---> Prints undefined in console**
console.log(body);
console.log(body.pagination.count);
let total_no_of_results = body.pagination.count;
let no_of_results;
for(no_of_results = 0; no_of_results < total_no_of_results; no_of_results++) {
//this.results[no_of_results] = new Recipes();
this.results[no_of_results] = body.data[no_of_results].embed_url; **---> Throws "Cannot set property '0' of undefined" error and stops execution**
//this.results.push(image);
}
console.log(this.results);
return this.results;
}
private handleErrorObservable (error: Response | any) {
console.error(error.message || error);
return Observable.throw(error.message || error);
}