【发布时间】:2020-09-24 14:03:10
【问题描述】:
我有一个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 是另一个对象,长度可变。我似乎无法检索该数据。
【问题讨论】:
-
要么声明
data:Array<any>=[]然后推送 ,this.data.push(data)要么声明data:any={}。 -
这只是将未定义的变量推送到数据数组中。我仍然无法解析它:(
标签: json angular typescript