In an Angular app, the naive way to show converted prices is to inject HttpClient into every component that needs a rate. Ten components on one page means ten identical requests. This post puts the rates behind one injectable service, shares a single request with shareReplay, and formats prices with a custom pipe.

It targets current Angular (standalone components, signals, built-in control flow) and calls your own backend, not the rate API directly.

Why your own backend sits in the middle

The browser should never see your rate API key. The keyed AllRatesToday API also sends no CORS headers, so a direct call from Angular fails anyway. Your backend adds the key, caches the result, and returns a small JSON shape your app controls. The proxy guide covers that side in detail. Here is the contract we assume:

GET /api/rates?base=USD 
{ "base": "USD", "time": "2026-12-06T10:15:00Z", "rates": { "USD": 1, "EUR": 0.92, "GBP": 0.79, "JPY": 151.2 } } 

The backend builds it from one upstream call that batches all targets:

GET https://allratestoday.com/api/v1/rates?source=USD&target=EUR,GBP,JPY Authorization: Bearer art_live_xxxxxxxx 

That returns a JSON array of { rate, source, target, time } rows, which the backend reshapes into the object above. You can get a free API key for it.

Providers

withFetch() makes HttpClient use the Fetch API, which is the recommended setup with SSR.

// src/app/app.config.ts import { ApplicationConfig } from '@angular/core'; import { provideHttpClient, withFetch } from '@angular/common/http'; export const appConfig: ApplicationConfig = { providers: [provideHttpClient(withFetch())], }; 

The service

// src/app/fx/exchange-rate.service.ts import { Injectable, inject } from '@angular/core'; import { HttpClient } from '@angular/common/http'; import { Observable, catchError, of, retry, shareReplay, tap, throwError } from 'rxjs'; export interface RateTable { base: string; time: string; rates: Record<string, number>; } @Injectable({ providedIn: 'root' }) export class ExchangeRateService { private readonly http = inject(HttpClient); private readonly ttlMs = 10 * 60_000; private readonly cache = new Map<string, { expires: number; table$: Observable<RateTable> }>(); private readonly lastGood = new Map<string, RateTable>(); rates(base = 'USD'): Observable<RateTable> { const hit = this.cache.get(base); if (hit && hit.expires > Date.now()) return hit.table$; const table$ = this.http.get<RateTable>('/api/rates', { params: { base } }).pipe( retry({ count: 2, delay: 1000 }), tap((table) => this.lastGood.set(base, table)), catchError((err) => { this.cache.delete(base); // let the next subscriber try again const stale = this.lastGood.get(base); return stale ? of(stale) : throwError(() => err); }), shareReplay({ bufferSize: 1, refCount: false }), ); this.cache.set(base, { expires: Date.now() + this.ttlMs, table$ }); return table$; } } 

How it behaves:

  • First subscriber triggers the HTTP request.
  • Every later subscriber within 10 minutes gets the replayed value from shareReplay, with no new request. That includes subscribers that arrive while the first request is still in flight.
  • refCount: false keeps the cached value alive even when all components unsubscribe, for example during route changes. With refCount: true the next subscriber would trigger a new request.
  • After the TTL, the next call creates a fresh observable. Old subscribers keep the old value; that is fine for display prices.
  • On failure, retry makes two more attempts one second apart. If they fail, we return the last good table if we have one, and remove the cache entry so a later call retries.

Your backend should cache too (rates upstream refresh about every 60 seconds; a 1-10 minute server cache is typical). The Angular cache saves round trips within a session; the server cache protects your quota across all users.

The pipe

A pure pipe only re-runs when its inputs change, which makes it cheap in templates. Since it cannot be async, we pass the rate table in as an argument.

// src/app/fx/convert-price.pipe.ts import { LOCALE_ID, Pipe, PipeTransform, inject } from '@angular/core'; import { RateTable } from './exchange-rate.service'; @Pipe({ name: 'convertPrice' }) export class ConvertPricePipe implements PipeTransform { private readonly locale = inject(LOCALE_ID); private readonly formatters = new Map<string, Intl.NumberFormat>(); transform(amount: number | null | undefined, table: RateTable | null, to: string): string { if (amount == null) return ''; // No rates yet, or unknown currency: show the base price. const base = table?.base ?? 'USD'; const rate = table?.rates[to]; const currency = rate ? to : base; const value = rate ? amount * rate : amount; return this.formatter(currency).format(value); } private formatter(currency: string): Intl.NumberFormat { let fmt = this.formatters.get(currency); if (!fmt) { fmt = new Intl.NumberFormat(this.locale, { style: 'currency', currency }); this.formatters.set(currency, fmt); } return fmt; } } 

We use Intl.NumberFormat directly instead of Angular's CurrencyPipe. CurrencyPipe needs locale data registered for every locale you support, while Intl already has it in every modern browser and in Node. Intl also handles minor units per currency: JPY gets no decimals, KWD gets three.

Standalone is the default for pipes in current Angular, so no standalone: true flag is needed.

A component that uses both

// src/app/pricing/pricing.component.ts import { Component, inject, signal } from '@angular/core'; import { toSignal } from '@angular/core/rxjs-interop'; import { ExchangeRateService } from '../fx/exchange-rate.service'; import { ConvertPricePipe } from '../fx/convert-price.pipe'; @Component({ selector: 'app-pricing', imports: [ConvertPricePipe], template: ` <label> Show prices in <select [value]="currency()" (change)="setCurrency($any($event.target).value)"> @for (c of currencies; track c) { <option [value]="c">{{ c }}</option> } </select> </label> @for (plan of plans; track plan.id) { <article> <h2>{{ plan.name }}</h2> <p>{{ plan.usd | convertPrice: rates() : currency() }} / month</p> </article> } @if (rates(); as table) { @if (currency() !== table.base) { <small>Approximate. Live mid-market rate from {{ table.time }}. Billed in USD.</small> } } `, }) export class PricingComponent { private readonly fx = inject(ExchangeRateService); readonly currencies = ['USD', 'EUR', 'GBP', 'JPY', 'CAD', 'AUD']; readonly currency = signal(localStorage.getItem('currency') ?? 'USD'); readonly rates = toSignal(this.fx.rates('USD'), { initialValue: null }); readonly plans = [ { id: 'starter', name: 'Starter', usd: 19 }, { id: 'team', name: 'Team', usd: 49 }, ]; setCurrency(code: string) { this.currency.set(code); localStorage.setItem('currency', code); } } 

toSignal subscribes once and unsubscribes when the component is destroyed. Before the response arrives, rates() is null, and the pipe shows USD prices. When the table arrives, the signal changes, the pure pipe re-runs, and prices switch to the chosen currency.

If you use SSR, localStorage does not exist on the server. Wrap that read in isPlatformBrowser or read the currency from a cookie instead.

Testing the service

provideHttpClientTesting lets you assert that ten subscribers produce one request.

// src/app/fx/exchange-rate.service.spec.ts import { TestBed } from '@angular/core/testing'; import { provideHttpClient } from '@angular/common/http'; import { HttpTestingController, provideHttpClientTesting } from '@angular/common/http/testing'; import { ExchangeRateService } from './exchange-rate.service'; describe('ExchangeRateService', () => { it('shares one request between subscribers', () => { TestBed.configureTestingModule({ providers: [provideHttpClient(), provideHttpClientTesting()], }); const service = TestBed.inject(ExchangeRateService); const http = TestBed.inject(HttpTestingController); const seen: number[] = []; for (let i = 0; i < 10; i++) { service.rates('USD').subscribe((t) => seen.push(t.rates['EUR'])); } http.expectOne('/api/rates?base=USD').flush({ base: 'USD', time: '2026-12-06T10:15:00Z', rates: { USD: 1, EUR: 0.92 }, }); expect(seen.length).toBe(10); expect(seen.every((r) => r === 0.92)).toBe(true); http.verify(); }); }); 

expectOne fails if there were two requests, so this test guards the caching behavior.

FAQ

Why not an HTTP interceptor that caches GET requests?
It works, but it caches everything by URL and hides the TTL in a generic place. A dedicated service keeps rate logic and fallback rules in one readable file.

Should I use a signal-based resource() instead of RxJS?
You can. httpResource is a good fit for one component. A shared service with shareReplay is still the simplest way to have many components share one cached request.

How often should the backend refresh?
Every 1-10 minutes is typical for display prices. Use the shorter end on checkout pages.

Can the pipe convert from any base?
Yes. Call fx.rates('EUR') and the table's base becomes EUR. The backend passes source=EUR upstream; any base currency works.