簡體   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