Q1: How can I extract an array of objects from a http response using map in Angular?
Q2: Is there a way to retrieve a specific object from a http response by utilizing map in Angular?
Below are the example URL, sample data, CurrencyAPIResponse, and Currency object for reference.
I have experimented with 2 methods and various alternatives, but none seem to be effective:
Q1: Extract an array of objects from a Map property within the Response object:
get(): Observable<Currency[]> {
return this.httpClient.get<CurrencyAPIResponse>('https://api.coindesk.com/v1/bpi/currentprice.json')
.pipe( map( response => Array.from( response.bpi.values())));
}
Q2: Retrieve a specific Currency object from a Response containing a Map property:
getOne(name: string): Observable<Currency> {
// @ts-ignore
return this.httpClient.get<CurrencyAPIResponse>('https://api.coindesk.com/v1/bpi/currentprice.json')
.pipe( map( response => response.bpi.get( name)));
}
Upon accessing the specified url, you will obtain an object with a map structure. The data is as follows:
{
"time": {
"updated": "Jun 5, 2022 12:04:00 UTC",
"updatedISO": "2022-06-05T12:04:00+00:00",
"updateduk": "Jun 5, 2022 at 13:04 BST"
},
"disclaimer": "Some text",
"chartName": "Bitcoin\"",
"bpi": {
"USD": {
"code": "USD",
"symbol": "$",
"rate": "29,698.5140",
"description": "United States Dollar",
"rate_float": 29698.514
},
"GBP": { ... },
"EUR": { ... }
}
}
The definition of my type and object is as follows:
Currency:
export class Currency {
code: string = '';
symbol: string = '';
rate: number = 0;
description: string = '';
rate_float: number = 0;
}
The CurrencyAPIResponse:
interface CurrencyAPIResponse {
"time": {
"updated": string, // or should this be a date?
"updatedISO": string,
"updateduk": string
},
"disclaimer": string,
"chartName": string,
"bpi": Map<string,Currency>
}