繁体   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