Reputation: 3085
I am trying to use angualrio to read from an array from a json file following this tutorial getting-started-with-angular-2-step-by-step-6-consuming-real-data-with-http/.
However I am getting the error
ERROR TypeError: undefined is not a function
The error occurs at this line
return response.json().map(this.toEvent)
The line above is different from the tutorial since http response
had been updated. reponse.json()
now return Body.json()
To simplify and mimic my issue I have created a json array x as following
let x = [{
eventId:132510417453240,
title:"Discover",
description:"do",
startDateTime:1512316800000,
endDateTime:1512320400000,
url:null
}]
And then using the line this.toEvent(x[0])
called the function below
private toEvent(r:any): Event{
let event = <Event>({
eventId: Number.parseInt(r.eventId),
title: r.title,
description: r.description,
startDateTime: Number.parseInt(r.startDateTime),
endDateTime: Number.parseInt(r.endDateTime),
url: r.url
});
console.log('Parsed event:', event);
return event;
}
Yet I end up with the error ERROR TypeError: this.toEvent is not a function
UPDATE (In response to @Yonexbat) toEvent is in the same scope I am calling it from. Both function are right after each other in the class as following
private toEvent(r:any): Event{
let event = <Event>({
eventId: Number.parseInt(r.eventId),
title: r.title,
description: r.description,
startDateTime: Number.parseInt(r.startDateTime),
endDateTime: Number.parseInt(r.endDateTime),
url: r.url
});
console.log('Parsed event:', event);
return event;
}
private mapEvents(response:Response): Event[]{
// The response of the API has a results
// property with the actual results
console.log(response)
console.log(response.json()[1])
console.log(response.text()[1])
let events : Event[] = [];
events = response.json()
//return events
return response.json().map((x) => this.toEvent(x))
}
Upvotes: 0
Views: 2814
Reputation: 3012
Well, this is not a solution but here I can format the text. I tried this and this works in Chrome:
import {Event} from './Event';
export class Test {
private toEvent(r: number): Event {
const event: Event = new Event();
return event;
}
public mapEvents(): Event[] {
const input = [1, 2, 3, 4, 5];
return input.map((x) => this.toEvent(x));
}
}
Possibly response.json() is a promise, and not an array. https://developer.mozilla.org/en-US/docs/Web/API/Body/json
Try
const toEventFunction = this.toEvent;
response.json().then(data => {
let result = data.map(x => toEventFunction(x));
});
Upvotes: 0