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

When I attempt to make an HTTP request in Angular, I can see my x-access-token, but for some reason the request is coming back

onTable(){ let headers = new HttpHeaders(); //headers.set('Content-Type', 'application/json'); //headers.set('x-access-token', this.token).set('Content-Type', 'application/json'); console.log("this is ...

Terminate the execution of the process.exec function

Currently, I have a function in my code that is responsible for executing a specific process. Here's how it looks: static async runTest() { await process.exec(`start ${currentDir}/forward.py`); } runTest(); Here's the thing – once this Python ...

Scrollbar width does not expand when hovered over

I am having trouble increasing the width of the scrollbar when hovering over it. However, I keep receiving an error in the console stating that 'scrollbar.addEventListener' is not a function. JAVASCRIPT setTimeout(function() { const scrollbar ...

Limiting multiple checkbox inputs in a React application can be easily achieved by utilizing React

Trying to create a form where the user can only check three boxes and uncheck them. The decrement on setCurrentData(currentData - 1) is not working as expected. Even after deselecting, the currentData remains at 3, preventing the user from checking any mo ...

Guide to integrating a Jquery third-party plugin in Angular 7

Recently, I integrated jQuery and a third-party plugin called "stiffChart" into my Angular 7 project. After installing jQuery and the plugin in my project, I declared them in angular.json file as well. However, when trying to call a method from the plugin, ...

The most effective method for monitoring updates to an array of objects in React

Imagine a scenario where an array of objects is stored in state like the example below: interface CheckItem { label: string; checked: boolean; disabled: boolean; } const [checkboxes, setCheckboxes] = useState<CheckItem[] | undefined>(undefined ...

Stop the closure of confirmation box by disabling the space key

I've been working on a website that features a table for users to interact with. Within one column of the table, there are input boxes where users can write notes. Below each input box, there is a save button to store the entered notes in a database. ...

Simultaneous AJAX, animated page loader

My website takes 3 seconds to load due to multiple Synchronous AJAX requests. To enhance user experience, I would like to implement a loading page with an animated GIF. Once the Ajax requests are completed and the page is fully loaded, the loading page sh ...

The JavaScript file fails to load when accessing port 8080

As I embark on my journey into backend development, please bear with me. Currently, I am working on a JavaScript program that retrieves text data from my localhost. I have set up an HTTP server using Node.js which serves as a regular HTTP server. The serve ...

Can you explain the distinction between any[] and [] in TypeScript?

Here is an example that successfully works: protected createGroups(sortedItems: Array<TbpeItem>): any[] { let groups: any[] = []; return groups; } However, the second example encounters a TypeScript error: type any[] not assignable to ...

The Javascript Switch statement is experiencing some functional issues

I am facing an issue where I need to handle different scenarios based on a decimal value, and I thought of using a Switch/case statement for this purpose. However, the code is not working as expected. Below is the snippet of code in question: var spread ...

Tips for obtaining the iframe #document with cheeriojs?

I've been struggling to scrape the anime videos page [jkanime], specifically with extracting the mp4 video formats embedded in an iframe #document. Despite trying to use cheerio for querying, I've only managed to retrieve src links from Facebook ...

The failure to build was due to the absence of the export of ParsedQs from express-serve-static-core

Encountered the error message [@types/express]-Type 'P' is not assignable to type 'ParamsArray'. Resolved it by installing specific packages "@types/express": "^4.17.8", "@types/express-serve-static-core": ...

Stop users from altering the model date while typing using the ui.bootstrap.datepicker-popup

I have implemented the datepicker-popup from Angular-UI Bootstrap in my application. Currently, when the user clicks and types in the text input field, $scope.dt gets updated with each keypress, causing the cursor position to reset to the end of the strin ...

Executing PHP scripts using Ajax

Check out the code snippet below: <?php //echo $this->Html->css(array('bootstrap', 'mark', 'style')); echo $this->Html->script(array('timer','swfobject','bootstrap.min.js')); // ...

Utilize JSON data from a service to populate a Bootstrap Modal

I need assistance with populating a Modal using the JSON values I received from a service call. The object structure is simple and understandable, like this: var object = [ {Value1: "Val1", Value2: "Val", Value3: [{a:"a",b:"b"}] }] The ajax call looks ...

The controller is providing a null response following an ajax Post request

I am having trouble with my ajax Post request targeting the edit action method in my controller. The issue is that none of the values are being populated, they all come back as null. What should be happening is that when the '.save-user' button ...

It seems like there is an issue with your network connection. Please try again

Recently, I made the switch to EndeavourOS, which is based on Archlinux. I completed all my installations without any issues and attempted to create a new NestJs project after installing NVM, Node's latest version, and the NestJs/cli. However, when I ...

Unlocking the potential: Clicking on all ng-if elements with matching text using Chrome console

I am currently trying to determine how to automatically click on all elements that have a specific state. The page appears to be built using Angular, although I am unsure of the exact version being used. My approach involves using the console in Chrome t ...

Error in Visual Studio when attempting to create a new Angular file without proper authorization

After setting up node, npm, and angular cli, I encountered an UnauthorizedAccess error when creating a new project in Visual Studio. Can someone please offer some assistance? Thank you, Please see the attached error image for reference ...