Angular application is not receiving any data from the external currency converter API

While working on a project, I encountered an issue with the API call not returning any conversion data. The Browser Network tab showed a status code of 200, but the method was OPTIONS instead of GET. Even though CORS is allowed for any origin, method, and header, it seems like the OPTIONS call might be preventing the GET call from going through. How can I troubleshoot this situation?

I am developing in Angular 5 and here is my code snippet:

getCurrencyWisePriceFromBDT(price: number, toCurrency: string): any {
  let currencyConversionUrl = "https://free.currencyconverterapi.com/api/v6/convert?q=BDT_";
  currencyConversionUrl = currencyConversionUrl + toCurrency;

  console.log(currencyConversionUrl);
  let rateInNewCurrency;
  this.http.get < any > (currencyConversionUrl).subscribe(data => {
    console.log(data);
    rateInNewCurrency = data.val;
    console.log(rateInNewCurrency);
    return rateInNewCurrency * price;
  });
}

Unfortunately, Chrome is giving me this error message:

Failed to load https://free.currencyconverterapi.com/api/v6/convert?q=BDT_USD: Request header field Authorization is not allowed by Access-Control-Allow-Headers in preflight response.

Answer №1

fetchPriceFromBDTInSpecificCurrency(price: number, targetCurrency: string): any {
  const currencyType = `BDT_${targetCurrency}`;
  const conversionAPI =`https://free.currencyconverterapi.com/api/v6/convert?q=${currencyType}`;
  console.log(conversionAPI);
  let rateInTargetCurrency;
  this.http.get < any > (conversionAPI).subscribe(data => {
    console.log(data);
    rateInTargetCurrency = data.results[currencyType].val;
    console.log(rateInTargetCurrency);
    return rateInTargetCurrency * price;
  });

rateInTargetCurrency will equal 0.01193 when calling

fetchPriceFromBDTInSpecificCurrency(50,'USD')
with arguments 50 and 'USD'. Does this meet your requirements? If it does, remember that the response object format after subscribing is as follows: data.results.BDR_USD.val based on the Currency specified in the URL.

Stackblitz Link

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

Creating a TypeScript schema with nested maps and arrays using Dynamoose

I'm currently in the process of developing a schema for a specific example: { "foods": [ { "fruits": [{ "apple": { "color": "red", ...

Strategies for passing multiple props to a function in React using TypeScript, such as useState([]) and useState(boolean)

Dealing with API Structure { "default": [ { "id": 1, "name": "A" }, { "id": 2, "name": "B" }, { "id": 3, "name" ...

Detecting clicks outside of a component and updating its state using Typescript in SolidJS

Hi there, I am currently learning the SolidJS framework and encountering an issue. I am trying to change the state of an element using directives, but for some reason it is not working. Can anyone point out what I might be doing wrong? You can find the ful ...

Guiding TypeScript to autonomously deduce the precise types of an object that implements a generic interface

Within this code snippet, TypeScript appears to be unaware of the specific type associated with userService.getByUserId in the final line. The expected type should be (userId: string) => ServiceResult<User>, but TypeScript is enforcing a more gene ...

Ensure that the PWA continues to operate in the background

I have developed a progressive web app using Angular 9. The purpose of the application is for trading, so the data changes constantly. Users can create statements and when these statements come true, the application sends notifications. I have also install ...

Unable to locate module or its associated type declarations for index.vue files

I made a change in my vite.config.ts to allow recognition of index.vue files as entry points. import { fileURLToPath, URL } from 'node:url' import vue from '@vitejs/plugin-vue' import { defineConfig } from 'vite' export defa ...

When combining Angular 5 with Angular Material Select and Reactive Forms, you may encounter a situation where the initial options

I'm currently facing an issue with a reactive form that contains multiple <mat-select> elements. Despite the fact that form.value shows the initial option, it is not displayed upon the form's initial load. Key component.ts: export cla ...

What is the best way to display converted value in Angular 8?

In my current project, I am utilizing .NET Core 2.2 for the backend and Angular 8 for the frontend. The scenario involves having integer values on the backend within a specified range. For example: [Required] [Range(1073741824, 1099511627776)] // ...

An error has occurred in the Angular application while trying to access the 'name' property in the AppComponent_Template

I'm encountering a challenge in my Angular application where I am receiving the following error message: javascript Copy code ERROR TypeError: Cannot read properties of undefined (reading 'name') This issue is present in the app.component. ...

Two lines in ChartJS with distinct fill gradients for each

I am facing an issue with ChartJS version 2.6 in my Ionic 3/Angular 4 app. I have set up a line chart config with 2 datasets, but I am struggling to apply individual fill gradients to each line. What I am aiming for is something like this: https://i.stac ...

Angular 7 ERROR: The SystemJS reference is missing

In the process of developing an Angular 7 project with systemjs for dynamic module loading, I encountered an issue. Upon attempting to utilize it, I encountered the following error: ERROR ReferenceError: SystemJS is not defined Within my package.json f ...

Typescript erroneously raises an issue indicating that the condition is expected to always be

Consider the code snippet below: class A { private foo : number = 3; public method () { if (this.foo === 3) { this.anotherMethod(); if (this.foo === 4) { console.log(this.foo); } ...

Guide on attaching custom functions to Vuetify stepper's previous and next buttons

I'm in the process of setting up a login flow using Vuetify. The idea is that in the first step, users enter their email address, in the second step they provide their password, and in the third step, they input TOTP information for a 2nd-factor authe ...

Transferring information from the parent component to the child using NgRx

One of the primary benefits of NgRx is its ability to streamline communication between components. The question at hand is: what is the most effective method for sharing data in this scenario? <div *ngIf=" content$ | async as content"> &l ...

Tips on distinguishing the faulty custom validation function in Reactive Forms

When dealing with multiple validators assigned to a formControl using formControlName as firstName, I often struggle to identify which validation is causing the error so that I can display the appropriate message. Below is a snippet of my custom validatio ...

A guide on setting a constant object for template usage

As I delve into constructing elasticsearch queries, I find myself eager to implement object templates to simplify the creation of POST bodies for my queries before they are sent to the data service. Although the initial query construction goes smoothly, I ...

How can I dynamically toggle the visibility of a dynamically generated <div> in Angular 8 based on its id?

When working with an Angular 8 component, I am dynamically generating a number of <table> elements from an input array. Each <table> includes a <tr> at the end which contains a hidden <div> along with a button. The goal is to togg ...

NextJS API routes consistently provide a status code of 200 upon execution

I am new to the concepts of Next.js, and I recently encountered an issue while attempting to fetch data from an API. The API is designed to check if a user session exists (i.e., if the user is logged in) and then returns a JSON response through a GET reque ...

Integrate Typescript compilation into the build process of Visual Studio 2017

I am currently working in VS2017 on a WebSite project where I have recently added a tsconfig.json file. I am wondering how I can automate the process of generating js files from ts files during the build phase? Interestingly, when I remove the tsconfig.js ...

Navigating to a precise path within Angular 6 by utilizing LoadChildren

When configuring routes in app.route, the following routes are set up: { path: 'homedetails', loadChildren: '../app/home/home-details/home-details.module#HomeDetailsModule', data: { preload: true, paramKey: & ...