Paweluk
Paweluk

Reputation: 11

How to get data from array in JSON - Angular 7+

I'm completely beginning in Angular and API. I'm trying to resolve some problem. My task is simple i guess. I have to get currency exchange rates data from NBP Web API. JSON file looks like:

enter image description here

I've found solution how to get some data from JSON, but i still have problem with array. The json file was converted to typescript and the result was :

enter image description here

So my Code look's like that:

Exchange.model.ts

 export interface Exchange {
  table: string;
  no: string;
  effectiveDate: string;
  rates: Rate[];
}

export interface Rate {
    currency: string;
    code: string;
    mid: number;
  }

app.component.ts

import { Component, OnInit } from '@angular/core';
import { Exchange, Rate } from './exchange.model';

import { DataService } from './data.service';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {

  exchanges$: Exchange;
  rates$: Rate;

  constructor(private dataService: DataService) {}

  ngOnInit() {
    return this.dataService.getExchanges().subscribe(data => this.exchanges$ = data)


  }

  ngOnInit2() {
    return this.dataService.getRates().subscribe(data => this.rates$ = data)


  }
}

and app.component.html

<div *ngFor='let exchanges of exchanges$'>
        <h2">{{exchanges.table}}  <br> {{exchanges.no}} <br> {{exchanges.effectiveDate}}</h2">
            {{exchanges.rates}}

</div>

The browser display the data like that:

enter image description here

The result is almost good. But the data from "rates" in JSON doesn't work.

"rates":[ 
{ 
"currency":"bat (Tajlandia)",
"code":"THB",
"mid":0.1261
},"

How to solve a problem? How to get data from array in JSON into typescript? What input into array in Exchange.module.ts? I know that, a question is long, but I wanted to display necessary code and images.

Upvotes: 0

Views: 293

Answers (1)

Aleš Doganoc
Aleš Doganoc

Reputation: 12082

You already have an Array as you see it displays a list of objects on your page. Since Rate is also an object you need to display its properties to see something meaningful.

If you want to display all the rates you can do another *ngFor for the rates like you do for exchanges.

For Example:

<div *ngFor="let exchanges of exchanges$">
   <h2>{{exchanges.table}}  <br> {{exchanges.no}} <br> {{exchanges.effectiveDate}}</h2>
   <div *ngFor="let rate of exchanges.rates">{{rate.code}} {{rate.mid}} {{rate.currency}}</div>
</div>

You did not explain very well what kind of output you want to get. If you want some additional processing it is better you move it inside the component code.

Upvotes: 1

Related Questions