2017-10-19 170 views
1

我正在学习如何在Angular 4.3中使用HTTPClientModule 我已经正确导入app.module.ts中,并且正在尝试创建一个http请求GET。这是我的app.component.ts错误TypeError:无法读取未定义的属性'名称'

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是不确定的?我怎样才能访问对象的元素,然后传入一个卡片数组? 感谢您的任何帮助

+0

你可以发布你的HTML模板的问题吗? –

+0

在我的角度项目中,我使用Http而不是HttpClient,也许它可以帮助你? –

+0

Http(或将会)不推荐使用,HttpClient是现在的方式... –

回答

3

该API返回对象数组,但您的Card界面正在定义具有card属性的对象。你需要使用的界面,将描述响应,就像这样:

interface Card { 
    cardClass: string; 
    cost: number; 
} 

interface CardArray { 
    [index: number]: Card; 
} 

this.http.get<CardArray>('https://api.hearthstonejson.com/v1/21517/enUS/cards.collectible.json').subscribe(data => { 
    console.log(data[0]); // first card 
    console.log(data); // all cards 
}); 

甚至更​​简单的方法:

this.http.get<Card[]>('https://api.hearthstonejson.com/v1/21517/enUS/cards.collectible.json').subscribe(data => { 
    console.log(data[0]); // first card 
    console.log(data); // all cards 
}); 
+0

谢谢!这确实解决了这个问题。我意识到卡接口有一些问题,但我无法'弄清楚为什么。 – aspnet82

0

尝试与json方法一起添加map方法只认购前:

this.http.get<Card>('https://api.hearthstonejson.com/v1/21517/enUS/cards.collectible.json') 
    .map(res => res.json()) 
    .subscribe(data => { 
    console.log(data.card); //This is not working returning undefined 
    console.log(data); //This is not working (removing <Card>) 
    }); 
+0

对于来自HttpClient的响应没有'json'方法。它会自动为你解析JSON响应(除非你告诉它不这样做)。 –

+0

对不起,我的错误,与旧的HttpModule – Andriy

+0

混淆,为了方便,我创建了一个https://plnkr.co/edit/JZiYveU76SfeNp31MRfL?p=preview,它只显示第一张显示卡@MartinAdámek – Andriy

相关问题