错误TypeError:无法读取未定义的属性“name”

时间:2017-10-19 13:43:23

标签: angular typescript xmlhttprequest undefined

我正在学习如何在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 个答案:

答案 0 :(得分:3)

API返回对象数组,但您的widget.init() 接口正在定义具有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
});

答案 1 :(得分:0)

尝试在订阅前添加map方法和json方法:

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>)
  });