【问题标题】:Load json data from backend into typescript/angular将 json 数据从后端加载到 typescript/angular
【发布时间】:2019-06-16 21:01:32
【问题描述】:

我正在尝试将 json 数据从后端服务加载到我的 Angular 应用程序。我想将数据加载/推送到数组中。下面是我的后端数据的样子

{   "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 调用

 fetchData(nameCity: NameCity) {

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

  }

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

【问题讨论】:

  • 试试这个this.eventMaster = [...this.eventMaster, ...data];而不是推送。

标签: angular typescript


【解决方案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));
}

【讨论】:

  • 根据我的理解,如果我使用的是 HTTPClient,那么 Angular 会为我提取正文。所以我不需要使用“地图”。这是不正确的吗?
  • 如果你的 json 数据结构与 angular 中声明的模型结构相对应,则不需要使用 map。在您的示例中,实际数据包含在Record 属性中,并且在您的模型中具有NamePlace 属性,而不是namecityName。你可以在你的问题代码中做一个console.log(data) 来检查它是否为空
【解决方案2】:

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

【讨论】:

  • 后端调用已完成,我在记录数据时可以在控制台中看到响应。它只是没有被加载到数组中
猜你喜欢
  • 2018-06-28
  • 1970-01-01
  • 2019-03-13
  • 1970-01-01
  • 2012-07-13
  • 1970-01-01
  • 2016-08-02
  • 1970-01-01
  • 2018-01-21
相关资源
最近更新 更多