0

在本教程getting-started-with-angular-2-step-by-step-6-sumption-real-data-with-http/之后,我正在尝试使用 angualrio 从 json 文件中读取数组。

但是我收到了错误

ERROR TypeError: undefined is not a function

错误发生在这一行

return response.json().map(this.toEvent)

由于http response已更新,上面的行与教程不同。reponse.json()现在回来Body.json()

为了简化和模仿我的问题,我创建了一个 json 数组 x 如下

let x = [{
  eventId:132510417453240,
  title:"Discover",
  description:"do",
  startDateTime:1512316800000,
  endDateTime:1512320400000,
  url:null
}]

然后使用this.toEvent(x[0])下面调用函数的行

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

然而我最终得到了错误ERROR TypeError: this.toEvent is not a function

更新(响应@Yonexbat)toEvent 与我调用它的范围相同。两个函数在类中紧随其后,如下所示

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

1 回答 1

0

好吧,这不是一个解决方案,但在这里我可以格式化文本。我试过这个,这在 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));
    }

}

可能 response.json() 是一个承诺,而不是一个数组。https://developer.mozilla.org/en-US/docs/Web/API/Body/json

尝试

const toEventFunction = this.toEvent;
response.json().then(data => {
   let result = data.map(x => toEventFunction(x));
});
于 2017-11-26T17:44:56.733 回答