将json数据从后端加载到typescipt / angular中

时间:2018-03-09 12:04:42

标签: angular typescript

我正在尝试将后端服务中的json数据加载到我的角度应用程序中。我想将数据加载/推送到数组中。以下是我后端的数据

{   "Record":[
  {
     "Name":"John",
     "Place":"Seattle"
  },
  {
     "Name":"AS2",
     "Place":"DC"
  }]}

这是我在typescript中的数组模型类

export class EventMaster {
  public name: string;
  public cityName: string;
  constructor (name: string, cityName: string){
    this.cityName = cityName;
    this.name = name;
  }
}

这是我用于从后端获取数据并加载到数组

中的打字稿代码
  private eventMaster: EventMaster[] = [
   new EventMaster('Loan', 'Approved' )
  ];

  onFetchData(form: HTMLFormElement){
    console.log(form);
    console.log(form.value);
    this.nameCity = new NameCity(form.value.name, form.value.city);

    this.fetchDataService.fetchData(this.nameCity).subscribe(
      (data: EventMaster[]) => {
        console.log(data);
        this.eventMaster.push(...data);
        console.log(this.eventMaster.length);
      }
        );

  }

这是我的http get call

 fetchData(nameCity: NameCity) {

  return this.http.get<EventMaster[]>(this.baseURL);

  }

当我尝试检查数组的长度时,它总是显示为1而不是2.我做错了什么?

2 个答案:

答案 0 :(得分:1)

您需要映射get API调用的结果

fetchData(nameCity: NameCity) {
    return this.http.get(this.baseURL).map((res: any) => res.Record.map(r=>new EventMaster(r.Name, r.Place));
}

答案 1 :(得分:0)

onFetchData是如何执行的?它可能只运行一次。还放置console.log(this.eventMaster.length);在此功能之外,尝试