2017-10-19 123 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

相關問題