List keys and values from JSON file

Issue

This is my json:

{
  "USD": "United States Dollar",
  "CHF": "Swiss Franc",
  "EUR": "Euro",
  "GBP": "British Pound Sterling"
}

And this is my interface:

export interface Currencies {
  currency: string
}

I have stored the JSON into src/assets/currencies.json and now I would like to list all keys and values.

This is what I have tried:

currencies.service.ts

constructor(private _http: HttpClient) { }
  
list(): Subscription {
  return this._http.get('./assets/currencies.json').subscribe(data => data);
}

list.component.ts

getAllCurrencies(): Subscription {
  console.log(this._currencyService.list())
  return this._currencyService.list();
}

Well, this is what I get, which is not what I expect:

enter image description here

What I want is just a simple list of keys and values. E.g.

Keys:

  • USD
  • CHF
  • EUR
  • GBP

Values:

  • United States Dollar
  • Swiss Franc
  • Euro
  • British Pound Sterling

How can I do this?

Solution

Something like this:

list(): Observable<Currencies> {
  return this._http.get('./assets/currencies.json');
}
getAllCurrencies(): Observable<Currencies> {
  return this._currencyService.list();
}
public currencies$ = this.getAllCurrencies();
<ng-container *ngIf="currencies$ | async as currencies">
  Keys:
  <ul>
    <li *ngFor="let item of currencies | keyvalue">
      {{item.key}}
    </li>
  </ul>

  Values:
  <ul>
    <li *ngFor="let item of currencies | keyvalue">
      {{item.value}}
    </li>
  </ul>
</ng-container>

Answered By – Eugene

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published