我有一个GET
返回以下 JSON 对象的请求:
{
"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,
}
}
为了以角度获取此响应,我有一个使用 API 来检索此对象的服务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?
如何从此 JSON 对象检索数据?该rates
发明的又一目的,是可变长度的。我似乎无法检索该数据。
显然,这是一个异步回复,因此可以使用 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();
}
接收函数如下所示:
data:any;
async requestData(base) {
this.data = await this.forex.latestRates(base);
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句