Justo Herrero
Justo Herrero

Reputation: 41

HttpClient not retrieving json data in Angular 6

I'm trying to use HttpClient from Angular 6 and I have been getting some issues.

My code looks like this:

TS

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%)',
    },
  ];

As you can see, I'm getting the info from an url and then I'm saving this info in an array. The problem is when I print this info I'm not getting the json object.

HTML:

<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>

However, If I put in html code the var directly:

 <div class="value">{{ btc.EUR }}</div>

It prints the info correctly. Have you any idea why is this happen?

Thanks in advance!

Upvotes: 0

Views: 166

Answers (1)

Vamsi Vempati
Vamsi Vempati

Reputation: 86

In the HTML snippet, async pipe has been used with progressInfoData but progressInfoData is not an observable. The observable in the array is just the value property. So async pipe should be used with value instead.

<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>

The change is here:

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

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

Since you are using async pipe on the template, you do not need to subscribe to it in the component - like Patricio Vargas mentioned above. So, you can get rid of the subscriptions in the component.

Upvotes: 2

Related Questions