【问题标题】:ERROR TypeError: Cannot read property 'name' of undefined错误类型错误:无法读取未定义的属性“名称”
【发布时间】: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


【解决方案1】:

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

【讨论】:

  • 谢谢!!!这确实解决了问题。我意识到卡界面有一些问题,但我不知道为什么。
【解决方案2】:

尝试在订阅前添加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>)
  });

【讨论】:

  • HttpClient 的响应中没有 json 方法。它会自动为您解析 JSON 响应(除非您告诉它不要这样做)。
  • 对不起,我的错误,与旧的 HttpModule 混淆
  • 为方便起见,我创建了一个 plunker plnkr.co/edit/JZiYveU76SfeNp31MRfL?p=preview,它只显示了建议的第一张卡片 @MartinAdámek
猜你喜欢
  • 1970-01-01
  • 2020-05-25
  • 2019-11-16
  • 1970-01-01
  • 1970-01-01
  • 2019-08-26
  • 1970-01-01
  • 2018-12-04
  • 2018-04-29
相关资源
最近更新 更多