Angular 2:ERROR TypeError:..不是函数

时间:2017-11-26 16:20:13

标签: angular angular2-http angular2-headers

我正在尝试使用angualrio从本教程getting-started-with-angular-2-step-by-step-6-consuming-real-data-with-http/之后的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))
  }

1 个答案:

答案 0 :(得分: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));
});