【发布时间】:2018-03-31 13:53:25
【问题描述】:
我正在学习如何在 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 未定义?我如何访问对象的元素,然后将其传递到卡片数组中? 感谢您的帮助
【问题讨论】:
-
你能发布你的 HTML 模板吗?
-
在我的 Angular 项目中,我使用 Http 而不是 HttpClient,也许对你有帮助?
-
Http 已(或将要)弃用,HttpClient 是现在要走的路......
-
@rinukkusu 是正确的,如果这不是您的域,您需要采取额外措施以允许与它通信。检查
subscribe的第二个参数(这是一个错误参数)。另请查看devtools以了解发生了什么。如果不是 CORS,则可能是访问远程站点时出现某种错误。 -
CORS 没问题,试了一下。
标签: angular typescript xmlhttprequest undefined