We generate our angular service for currencies by running.
ng g service services/currency
This will generate our currency service and service as follows
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { CURRENCY_API_URL_ENDPOINT } from '../constants';
@Injectable()
export class CurrencyService {
constructor(private http: HttpClient) {}
public getCurrencyData(payload: string = null) {
return this.http.get(CURRENCY_API_URL_ENDPOINT + payload);
}
}
Next, we will generate a new component called currency where we will import our new service and inject it for retrieving currency-related data.
The complete component file is shown below. The component will have one input prop called currency where we can pass the currency
whose exchange rates we want to retrieve. When the data is retrieved, we will keep it in currencyList
import { Component, OnInit, Input } from '@angular/core';
import { CurrencyService } from '../../services/currency.service';
import { Currency } from '../../models';
@Component({
selector: 'app-currency',
templateUrl: './currency.component.html',
styleUrls: ['./currency.component.css'],
providers: [CurrencyService],
})
export class CurrencyComponent implements OnInit {
@Input() currency: string = 'Rupees';
public currencyList: Currency;
constructor(private currencyService: CurrencyService) {}
ngOnInit(): void {
this.currencyService
.getCurrencyData(this.currency)
.subscribe((data: Currency) => {
this.currencyList = data;
});
}
}
We finish up by building a template to display our currency data.
<div class="h6">Below are exchange rates for 1 {{ currency }}</div>
<ul class="list-group">
<li class="list-group-item" *ngFor="let item of currencyList">
<ul class="list-group">
<li class="list-group-item inner">Currency :{{ item.currency }}</li>
<li class="list-group-item inner">Price : {{ item.value }}</li>
</ul>
</li>
</ul>
We will use this component on the home page of our news site.