繁体   English   中英

如何从Angular7中的JSON文件中获取和使用数据

[英]How to fetch and use data from a JSON file in Angular7

我正在尝试从JSON文件中获取数据并以表格形式显示该数据

JSON文件链接: https : //raw.githubusercontent.com/datameet/railways/master/trains.json

我正在尝试以下代码。 但是它在fetchdata.component.ts文件中返回以下错误:

类型“对象”上不存在属性“ json”。

fetchdata.component.ts

import { Component, OnInit } from '@angular/core';
import { HttpClient } from '@angular/common/http';

@Component({
  selector: 'app-fetchdata',
  templateUrl: './fetchdata.component.html',
  styleUrls: ['./fetchdata.component.css']
})

export class FetchdataComponent implements OnInit {

  private _trainUrl = "https://raw.githubusercontent.com/datameet/railways/master/trains.json
";
  items : any;
  constructor(private http:HttpClient) {
    this.http.get( this._trainUrl)
      .subscribe(res => this.items = res.json());
    console.log(this.items);
  }

  ngOnInit() {
  }

}

fetchdata.component.html

<select>
  <option  *ngFor="let item of items" [value]="item.properties.from_station_name">{{item.properties.from_station_name}}</option>
</select>

请帮忙。

回应可能不是您所想。 我建议您console.log()查询的响应,以查看其实际外观:

    items : any;
    constructor(private http:HttpClient) {
      this.http.get( this._trainUrl)
        .subscribe(res => {
          this.items = res.features; 
          console.log("Response", res);
          console.log(res.features)
        });
    }

您会看到您实际上在控制台中得到了以下信息:

{type: "FeatureCollection", features: Array(5208)}
features: (5208) [{…}, …]
type: "FeatureCollection"
__proto__: Object

因此,您可以将项分配给features键,因为这是您真正需要的:

 constructor(private http:HttpClient) {
      this.http.get( this._trainUrl)
        .subscribe(res => {
          this.items = res["features"]; 
        });
    }

然后您的选择选项应显示。

只是让您知道,这不是完美的方法,但是对于像这样的小示例来说,它的效果很好。 我建议您将来考虑为任何请求创建服务(在构造函数中进行操作不是最好的方法),并看看RxJS库

Angular的HttpHttpClient模块之间有区别,它们的导出方式也不同。

  1. Http - >是核心模块,其需要用户调用res.json() 这在Angular 4.0之前是常见的。

  2. HttpClient >是自4.0版以来的新模块。 它将通信默认为json,因此您无需显式调用res.json()

简而言之,将res.json()更改为res为您解决问题。

this.items = res; 应该没事。

另外,作为一种好的做法,请使用ngOnInit生命周期方法而不是构造函数进行任何Http调用。

如果您简单地执行this.http.get无需调用.json()函数。 Angular为您做到了。 只需执行this.items = res 这样就可以了。

UPD:您的JSON对象本身不是数组。 您还需要通过以下方式更新模板:

<select>
  <option  *ngFor="let item of items.features" [value]="item.properties.from_station_name">{{item.properties.from_station_name}}</option>
</select>

为什么要这样做this.items = res.json() 为什么不只是this.items = res res应该已经保存了从GET请求返回的JSON对象。 如果确实是字符串,请尝试this.items = JSON.parse(res)

你能试一下吗 :

private _trainUrl = "https://raw.githubusercontent.com/datameet/railways/master/trains.json";
  items : any;
constructor(private http:HttpClient) {}


  ngOnInit() {
    this.http.get( this._trainUrl).subscribe(res => {
      this.items = res;
      console.log(this.items);
    });
  }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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