简体   繁体   English

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

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

I am trying to fetch data from a JSON file and display that data in the form 我正在尝试从JSON文件中获取数据并以表格形式显示该数据

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

I am trying with the below code. 我正在尝试以下代码。 But it returns following error in fetchdata.component.ts file: 但是它在fetchdata.component.ts文件中返回以下错误:

Property 'json' does not exist on type 'Object'. 类型“对象”上不存在属性“ json”。

fetchdata.component.ts 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 fetchdata.component.html

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

Please help. 请帮忙。

The response probably isn't what you think. 回应可能不是您所想。 I suggest you console.log() the response of your query to see what it actually looks like: 我建议您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)
        });
    }

You'll see that you actually get something like this in your console: 您会看到您实际上在控制台中得到了以下信息:

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

So you can assign your items to the features key as that's what you really need: 因此,您可以将项分配给features键,因为这是您真正需要的:

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

Then your select options should show up. 然后您的选择选项应显示。

Just letting you know, this isn't the perfect way to do it but it works fine for a small example like this. 只是让您知道,这不是完美的方法,但是对于像这样的小示例来说,它的效果很好。 I suggest you look into creating a service for any request in the future (doing it in the constructor isn't the best way) and have a look at the RxJS library 我建议您将来考虑为任何请求创建服务(在构造函数中进行操作不是最好的方法),并看看RxJS库

There is a difference between Angular's Http and HttpClient module and they are also exported differently. Angular的HttpHttpClient模块之间有区别,它们的导出方式也不同。

  1. Http -> is the core module which requires the user to call res.json() . Http - >是核心模块,其需要用户调用res.json() This was common prior to Angular version 4.0. 这在Angular 4.0之前是常见的。

  2. HttpClient -> is new module since version 4.0. HttpClient >是自4.0版以来的新模块。 It defaults the communication to json and hence you don't need to call res.json() explicitly. 它将通信默认为json,因此您无需显式调用res.json()

In short, changing from res.json() to just res will fix the issue for you. 简而言之,将res.json()更改为res为您解决问题。

ie this.items = res; this.items = res; should be fine. 应该没事。

Also, as a good practice use the ngOnInit lifecycle method instead of the constructor to make any Http calls. 另外,作为一种好的做法,请使用ngOnInit生命周期方法而不是构造函数进行任何Http调用。

You don't need to call .json() function in case you doing plain this.http.get . 如果您简单地执行this.http.get无需调用.json()函数。 Angular does that for you. Angular为您做到了。 Simply do this.items = res . 只需执行this.items = res That will do the trick. 这样就可以了。

UPD: your JSON object is not an array itself. UPD:您的JSON对象本身不是数组。 You as well need to update your template in the following way: 您还需要通过以下方式更新模板:

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

Why do you do this.items = res.json() ? 为什么要这样做this.items = res.json() Why not just this.items = res ? 为什么不只是this.items = res res should already hold the JSON object returned from the GET request. res应该已经保存了从GET请求返回的JSON对象。 If it is indeed a string try this.items = JSON.parse(res) . 如果确实是字符串,请尝试this.items = JSON.parse(res)

Can you try : 你能试一下吗 :

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