简体   繁体   中英

Angular 2: ERROR TypeError: .. is not a function

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))
  }

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));
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM