我正在学习如何在Angular 4.3中使用HTTPClientModule我已经在app.module.ts中正确导入了,我正在尝试进行http请求GET . 这是我的app.component.ts
import { Component, OnInit } from '@angular/core';
import { HttpClient} from '@angular/common/http';
interface Card {
card: [{
cardClass: string,
cost: number;
}];
}
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
constructor(private http: HttpClient) {}
ngOnInit(): void {
this.http.get<Card>('https://api.hearthstonejson.com/v1/21517/enUS/cards.collectible.json').subscribe(data => {
console.log(data.card); //This is not working returning undefined
console.log(data); //This is not working (removing <Card>)
});
}
}
为什么data.card未定义?我如何访问这里的对象元素然后传递到卡片阵列?谢谢你的帮助
2 回答
API返回对象数组,但
Card
接口正在定义具有card
属性的对象 . 您需要使用将描述响应的接口,如下所示:甚至更简单的方法:
尝试在订阅之前添加
map
方法和json
方法: