首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >HttpClient在Angular 6中未检索json数据

HttpClient在Angular 6中未检索json数据
EN

Stack Overflow用户
提问于 2018-08-23 07:01:00
回答 1查看 149关注 0票数 0

我正在尝试使用Angular 6中的HttpClient,但我遇到了一些问题。

我的代码如下所示:

TS

代码语言:javascript
复制
btc = this.http.get<any>(this.btcurl).subscribe(res => this.btc = res);

  eth = this.http.get<any>(this.ethurl).subscribe(res => this.eth = res);

  ltc = this.http.get<any>(this.ltcurl).subscribe(res => this.ltc = res);

  progressInfoData = [
    {
      title: 'Bitcoin (BTC) Price',
      value: this.btc,
      activeProgress: 70,
      description: 'Better than last week (70%)',
    },
    {
      title: 'Ethereum (ETH) Price',
      value: this.eth,
      activeProgress: 30,
      description: 'Better than last week (30%)',
    },
    {
      title: 'Litecoin (LTC) Price',
      value: this.ltc,
      activeProgress: 55,
      description: 'Better than last week (55%)',
    },
  ];

如您所见,我从一个url中获取信息,然后将此信息保存在一个数组中。问题是当我打印这个信息时,我没有得到json对象。

HTML

代码语言:javascript
复制
<nb-card size="medium">
  <nb-card-body>
    <div class="progress-info" *ngFor="let item of progressInfoData | async">
      <div class="title">{{ item.title }}</div>
      <div class="value">{{ item.value.EUR }}</div>
      <nb-progress-bar [value]="item.activeProgress"></nb-progress-bar>
      <div class="description">
        <bdi>{{ item.description }}</bdi>
      </div>
    </div>
  </nb-card-body>
</nb-card>

但是,如果我将var直接放入html代码中:

代码语言:javascript
复制
 <div class="value">{{ btc.EUR }}</div>

它可以正确地打印信息。你知道为什么会这样吗?

提前感谢!

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2018-08-23 09:01:10

在HTML代码片段中,async管道已与progressInfoData一起使用,但progressInfoData不是可观察到的。数组中的观察值只是value属性。因此,应该在value中使用async管道。

代码语言:javascript
复制
<nb-card size="medium">
  <nb-card-body>
    <div class="progress-info" *ngFor="let item of progressInfoData">
      <div class="title">{{ item.title }}</div>
      <div class="value">{{ (item.value | async)?.EUR }}</div>
      <nb-progress-bar [value]="item.activeProgress"></nb-progress-bar>
      <div class="description">
        <bdi>{{ item.description }}</bdi>
      </div>
    </div>
  </nb-card-body>
</nb-card>

变化如下:

<div class="progress-info" *ngFor="let item of progressInfoData">

<div class="value">{{ (item.value | async)?.EUR }}</div>

因为您在模板上使用async pipe,所以不需要在上面提到的Patricio Vargas这样的组件中订阅它。因此,您可以删除组件中的订阅。

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/51976277

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档