Issue with manipulating currency conversion data

Currently, I am embarking on a project to develop a currency conversion application resembling the one found on Google's platform. The main hurdle I am facing lies in restructuring the data obtained from fixer.io to achieve a similar conversion method as seen on Google. To access the necessary data for this task, I can only utilize the designated endpoint provided by fixer.io: .

Beneath, you will find snippets of my code which might offer additional clarity. Furthermore, a working example has been set up using Stackblitz here: https://stackblitz.com/edit/angular-9-material-starter-o9yvuu?file=src/app/app.component.ts

Service

//list endpoint from Fixer.io
currencyRates(): Observable<any> {
    return this.http.get(this.baseURL + this.accessKey);
}

TS

  //call endpoint and manipulate data to use on HTML
  public currencies: any;
  public currenciesArr: any;

  getCurrencies() {
    this.currencyService.currencyRates().subscribe({
      next: (v) => {
        this.currencies = v;
        let result = Object.keys(this.currencies.rates).map((key) => 
          [String(key), this.currencies.rates[key]]
        );
        this.currenciesArr = result;
        console.log(this.currenciesArr);
      },
      error: (e) => console.error(e),
      complete: () => console.info('complete') 
   });
  }

HTML

    <mat-form-field class="form-field" appearance="outline">
      <mat-label> Input Currency
      </mat-label>
      <input matInput formControlName="input" required>
    </mat-form-field>
    <mat-form-field appearance="fill">
        <mat-label>Select an option</mat-label>
        <mat-select >
          <mat-option *ngFor="let item of currenciesArr" [value]="item">{{item}}</mat-option>
        </mat-select>
    </mat-form-field>
    <mat-form-field class="form-field" appearance="outline">
      <mat-label> Output Currency
      </mat-label>
      <input matInput formControlName="output" type="output" required>
    </mat-form-field>
    <mat-form-field appearance="fill">
      <mat-label>Select an option</mat-label>
      <mat-select >
        <mat-option *ngFor="let item of currenciesArr" [value]="item">{{item}}</mat-option>
      </mat-select>
  </mat-form-field>

The original data fetched from the endpoint had a distinct structure which I modified to fit into my dropdown menus through the use ofObject.keys.

{
    "success": true,
    "timestamp": 1645249562,
    "base": "EUR",
    "date": "2022-02-19",
    "rates": {
        "AED": 4.158769,
        "AFN": 104.057478,
        "ALL": 121.54654
    }
}

As I delve deeper into this project, I find myself pondering whether the creation of two arrays is the best approach - one for storing currency names and the other for their values. Any guidance or assistance in navigating this challenge would be greatly appreciated.

Amidst my current brainstorming session, I am contemplating various solutions, but uncertainty clouds my judgement. Your insight could bring clarity to this perplexing issue I currently face.

Answer №1

Alright, the information you currently possess is sufficient, all that's required now is a bit of clever maneuvering :)

To begin with, I would create an array (let's call it allCurrencies) containing currency objects structured like this:

{ currency: 'XYZ', baseRate: '1234' }
. Here, 'XYZ' represents the names extracted from your 'rates' field, and '1234' signifies the conversion rate against EUR for each respective currency.

Next, in the template, I'd loop through this array to populate dropdown options with the values of 'currency'. Additionally, I might consider making the output currency input field readonly as an option.

Moving on, whenever the 'input currency' is modified or selected, and the associated text input isn't empty or null, I'd promptly convert the amount to EUR within the .ts file using the 'baseRate' from allCurrencies. This resulting new amount can be referred to as convertedOriginal.

Lastly, upon changing the 'output currency' selection (assuming the 'input currency' has been chosen and the corresponding text input isn't blank), I'd proceed to convert the value of convertedOriginal to match the rate of the newly selected output currency.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Issue with executing Jquery in PUG file: The $ sign is not being recognized despite jQuery being imported

I am encountering an issue where my jQuery code placed inside a pug template is not executing as expected. Despite including the jQuery file, when trying to run a jQuery function, I receive the error below: 40| P 41| ...

In the following command, where is the PORT stored: ~PORT=8080 npm App.js?

section: Let's consider the following code snippet located in the App.js file: console.log(`This is the port ${process.env.PORT}`); Is there a method to retrieve the value of PORT from outside the running process? ...

What steps can I take to stop jQuery's $.getJSON function from converting my AJAX response keys into integers?

I am facing an issue where JQuery is changing the type of keys in a JSON response object from text to integer when populating a select box. This causes the response object to be reordered based on the numeric indexes, disrupting the order of the select box ...

MacGyver's innovative Angular mac-autocomplete directive fails to properly auto-complete

I have incorporated the .css and .js files for MacGyver in my HTML document. Additionally, I have added 'Mac' as a dependency in my Angular application. The following code snippet is included in my HTML: <mac-autocomplete ng-model="selected" ...

Having trouble sending a function as a prop to a child component in React

Something odd is happening, I'm confident that the syntax is correct, but an error keeps popping up: Error: chooseMessage is not a function // MAIN COMPONENT import React, { useState } from 'react' export default function LayoutMain(prop ...

Addressing the issue of Google Charts legends overlapping

As a newcomer to Stackoverflow and Google Charts, I am encountering an issue in one of my projects that utilizes the Google Charts API. Specifically, I am trying to display two legends on the chart but they are overlapping in the preview. Despite explorin ...

Ways to address observables in Angular in a manner similar to deferred objects

Transitioning from AngularJS to Angular has posed a challenge for me, especially when it comes to moving from promises to observables. Below is an example of my code in AngularJS: var deferred = $q.defer(), frame = document.createElement('newFrame ...

Editable Table Component in React

I've developed a React table as shown below: const CustomTable = ({content}) => { return ( <table className="table table-bordered"> <thead> <tr> <th>Quantity</ ...

Methods for defining a variable in React with Typescript without encountering the "Index signature is missing in type" issue

I am facing an issue while trying to declare a variable 'reports' and assigning it to an array of arrays containing string and number types. The problem arises when I try to assign it, resulting in errors. ... // Retrieving data from an API let ...

What is the best way to approach writing a shared value that is utilized across multiple files in Angular?

I am currently implementing Angular for the front end of my project. One challenge I'm facing is managing a single value, such as a 'role id', that needs to be used in multiple .ts files within Angular. Can anyone suggest an efficient way ...

Enable express to disregard specific URL modifications

I'm currently working on creating a Single Page App using Express. One of the challenges I am facing is that the Express route feature forces the view to be re-rendered every time the URL changes and a GET request is sent to the server. My code typica ...

Utilizing type guards in prop functions for conditional rendering within React TypeScript adds an extra layer

In my code, I am conditionally rendering a Button. However, I encountered an issue on line 7 where TypeScript is indicating that the first parameter of the exportExcel function may be null even though it should not be, considering the conditional render lo ...

Error: Attempting to access property 'setData' of an undefined object results in a TypeError [Slider]

I encountered an error with my slider that says Uncaught TypeError: Cannot read property 'setData' of undefined. The error occurs when I use material ui as a component along with redux-form. This issue happens specifically when the slider is bein ...

Storing a collection of objects in session storage

I've been struggling to save an array containing the items in my online shopping cart. Even though both the object and the array are being filled correctly, when I check the sessionStorage, it shows an array with an empty object. I've spent a lot ...

Updating an Object in vue.js Upon Click Event to Add a New Value

I currently have a code snippet that looks like the following: arr = [ { val1: a, val2: b }, { val1: a, val2: b }, { val1: a, val2: b } ] <div v-for="single in arr"> <button v-on:click="addSome"></button> </div> When I c ...

What is the best way to implement client-side shopping cart calculations using jQuery?

https://i.stack.imgur.com/aOajr.png Here is the content of my shopping cart. Below, I will explain the flow. [product image clicked] -> ajax request fetches details from database for that particular product id and appends (product name,id and price a ...

Inconsistent reliability of Loopback-context prompts the search for an alternative solution

After encountering some reliability issues with the loopback-context package, I decided to try an alternative approach. Instead of relying on setting the current user object in my middleware using loopback-context, I opted to fetch the accessToken from the ...

Running a Python script using Node.js

I'm having trouble running a machine learning script from my node.js application using the child-process core module as described here However, I am unable to receive any output from script.stdout.on. The versions I am using are Node v12.5.0 and pyt ...

Utilize static information within an Angular component

I'm working on an Angular project in my localhost and I want to have two routed components that share the same data. One component will display the data, while the other will handle the data. In simpler terms, I need two webpages: one with an input f ...

The assertion that 'd3Ctrl' is not a valid function, but instead is undefined

Although several people have raised the same issue before and I've attempted their solutions, I still can't seem to resolve it. My problem involves using d3, but I keep encountering this error: app.js var app = angular.module('myApp', ...