簡體   English   中英

如何從 Angular 9 中的 GET 請求讀取 JSON object 響應?

[英]How to read a JSON object response from GET request in Angular 9?

我有一個返回以下 JSON object 的GET請求:

{
    "success": true,
    "timestamp": 1591353365,
    "base": "EUR",
    "date": "2020-06-05",
    "rates": {
        "AED": 4.16005,
        "AFN": 85.969034,
        "ALL": 124.045327,
        "AMD": 540.380668,
        "ANG": 2.009928,
    }
}

要在 angular 中獲得此響應,我有一項服務使用 API 通過http.get()檢索此 object:

import { Injectable } from '@angular/core';
import { HttpClient } from "@angular/common/http";

@Injectable({
  providedIn: 'root'
})
export class ForexService {

  api_key = 'my personal key' //Can't give away the key

  constructor(private _http: HttpClient) { }

  latestRates() {
    return this._http.get('http://data.fixer.io/api/latest?access_key='+this.api_key);
  }
}

我有一個組件文件訂閱了這個可觀察的服務:

import { Component, OnInit } from '@angular/core';
import { ForexService } from "../forex.service";

@Component({
  selector: 'app-forexapi',
  templateUrl: './forexapi.component.html',
  styleUrls: ['./forexapi.component.css']
})
export class ForexapiComponent implements OnInit {

  data:Array<any>;
  constructor(private forex: ForexService) {
    console.log('Forex component constructor called');
  }

  ngOnInit(): void {
    this.forex.latestRates().subscribe(data => this.data = data);
    }
  }

當我這樣做時,我收到錯誤消息,指出The 'Object' type is assignable to very few other types. Did you mean to use the 'any' type instead? The 'Object' type is assignable to very few other types. Did you mean to use the 'any' type instead?

如何從這個 JSON object 中檢索數據? rates是另一個 object 並且長度可變。 我似乎無法檢索該數據。

使用 Angular 2+ 的好處是它使用TypeScript並且您還可以在代碼中執行強typing ,例如定義 latestRate 的返回類型,如下所示:

 latestRates(): Observable<Rate[]> {
 return this._http.get('http://data.fixer.io/api/latest?access_key='+this.api_key)
    .map(result=>result.rates)

 }

還創建一個 model 的rate ,類似於rate.model.ts並將其定義為響應 object rate (即您從 API EndPoint 獲得的 object):

export interface ResponseObject {
  success: number;
  timestamp: string;
  base: string;
  date: Date;
  rates: Rate;
 }
export interface Rate  {
    aed: number;
    afn: number;
    all: number;
}

將其保存為rate.model.ts 之后,在你的 ngOnInit 中:

ngOnInit(): void {
      this.forex.latestRates().subscribe(rates => this.data = rates);
}

旁注:盡量避免使用any作為type

問題在於ForexapiComponent中的data變量數據類型;

您的返回響應將數據作為對象,但您將data變量聲明為項目數組,因此 Typescript 將期望項目數組而不是對象

為了快速修復,您可以將data類型更改為任何此類data:any

您將data定義為data:Array<any>; 即一個數組

但是你得到的數據是JSON Object

使用data:any;

我有一個GET請求,它返回以下 JSON object:

{
    "success": true,
    "timestamp": 1591353365,
    "base": "EUR",
    "date": "2020-06-05",
    "rates": {
        "AED": 4.16005,
        "AFN": 85.969034,
        "ALL": 124.045327,
        "AMD": 540.380668,
        "ANG": 2.009928,
    }
}

為了在 angular 中得到這個響應,我有一個服務使用 API 來檢索這個 object 使用http.get()

import { Injectable } from '@angular/core';
import { HttpClient } from "@angular/common/http";

@Injectable({
  providedIn: 'root'
})
export class ForexService {

  api_key = 'my personal key' //Can't give away the key

  constructor(private _http: HttpClient) { }

  latestRates() {
    return this._http.get('http://data.fixer.io/api/latest?access_key='+this.api_key);
  }
}

而且我有一個訂閱此服務可觀察的組件文件:

import { Component, OnInit } from '@angular/core';
import { ForexService } from "../forex.service";

@Component({
  selector: 'app-forexapi',
  templateUrl: './forexapi.component.html',
  styleUrls: ['./forexapi.component.css']
})
export class ForexapiComponent implements OnInit {

  data:Array<any>;
  constructor(private forex: ForexService) {
    console.log('Forex component constructor called');
  }

  ngOnInit(): void {
    this.forex.latestRates().subscribe(data => this.data = data);
    }
  }

當我這樣做時,我收到The 'Object' type is assignable to very few other types. Did you mean to use the 'any' type instead? The 'Object' type is assignable to very few other types. Did you mean to use the 'any' type instead?

如何從此 JSON object 檢索數據? rates是另一個 object 並且長度可變。 我似乎無法檢索該數據。

顯然,這是一個異步回復,因此可以使用 async-wait 方法解決。

這就是我更改服務代碼的方式:

latestRates(base: string = "USD"): Promise<any> {
    //return this._http.get('http://data.fixer.io/api/latest? access_key='+this.api_key+'&base='+base).toPromise();
    return this._http.get('https://api.exchangeratesapi.io/latest?base='+base).toPromise();
  }

接收 function 看起來像:

data:any;
async requestData(base) {
    this.data = await this.forex.latestRates(base);
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM