You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Angular响应式表单货币转换器请求无响应问题求助

Angular响应式表单货币转换器请求无响应问题排查

问题描述

使用Angular响应式表单实现货币转换器,表单字段可正常读取,但向后端发起请求后始终无法收到响应,需排查问题并修复。

现有代码

HTML模板

<div class="selection-container">
<form [formGroup]="currencyForm" class="form-box">
  <div class="box">
  <input type="text" formControlName="amount">
  <select name="" id="country1" formControlName="changebase">
    <option value="USD">US dollar</option>
    <option value="EUR">Euro</option>
    <option value="UAH">Ukranian Grivna</option>
  </select>
</div>
  <p class="title">  to </p>
  <select name="" id="country1" formControlName="tocountry">
    <option value="USD">US dollar</option>
    <option value="EUR">Euro</option>
    <option value="UAH">Ukranian Grivna</option>
  </select>
<button (click)="convert()"> Submit</button>
</form>

<div class="result-container">
  <p class="title">{{changebase}} <span>=</span>{{result}} {{tocountry}}</p>
</div>
</div>

数据服务代码

import { Injectable } from '@angular/core';
import {HttpClient} from "@angular/common/http"

@Injectable({
  providedIn: 'root'
})
export class CurrencydataService {

  constructor(private http:HttpClient) { }
  getcurrencydata(country1:string){
    let url ="https://api.exchangerate.host/latest?base=USD"+country1
    return this.http.get(url)
  }
}

组件逻辑代码

export class CurrencyReactiveComponent implements OnInit {
  currjson:any="";
  amount:number=1;
  changebase:string= "";
  tocountry:string="";
  result:number=1

  createFormGroup(){
    return new FormGroup({
      amount: new FormControl(""),
      changebase: new FormControl(""),
      tocountry:new FormControl("")
    });

  }
  currencyForm: FormGroup;


    constructor(private currency:CurrencydataService) {
      this.currencyForm =this.createFormGroup()

     }

    ngOnInit()  {
    //this.getcurrencydata()
    }

    convert(){
      this.currency
      .getcurrencydata(this.changebase)
      .subscribe(data=>{
        this.currjson= JSON.stringify(data);
        this.currjson= JSON.parse(this.currjson);
        console.log(this.currencyForm.value)
        if (this.tocountry ==="USD"){
          this.result = this.currjson.rates.USD * (this.amount)

        }


        if (this.tocountry ==="EUR"){
          this.result = this.currjson.rates.EUR * (this.amount)
        }


        if (this.tocountry ==="UAH"){
          this.result = this.currjson.rates.UAH * (this.amount)
        }
      })

    }
}

错误排查与修复方案

1. API URL拼接错误

服务中getcurrencydata方法的URL拼接逻辑错误,原代码会把传入的货币代码直接拼在base=USD后面,生成类似https://api.exchangerate.host/latest?base=USDEUR的无效URL,导致API返回400错误。

修正服务代码:

getcurrencydata(country1:string){
  // 使用传入的货币代码作为base参数的值
  let url = `https://api.exchangerate.host/latest?base=${country1}`;
  return this.http.get(url);
}

2. 未从响应式表单中读取字段值

组件中定义的changebase、tocountry、amount变量未与表单控件绑定,始终为空值,导致请求参数无效,且后续计算逻辑无法触发。

3. 移除多余的JSON转换

HttpClient默认会将API响应解析为JSON对象,无需执行JSON.stringify和JSON.parse的冗余操作,直接使用响应数据即可。

4. 添加错误回调

在subscribe中添加error回调,能在请求失败时打印错误信息,快速定位问题(比如URL无效、网络问题等)。

修正后的组件完整代码

import { Component, OnInit } from '@angular/core';
import { FormGroup, FormControl } from '@angular/forms';
import { CurrencydataService } from './path-to-your-service'; // 替换为实际服务路径

export class CurrencyReactiveComponent implements OnInit {
  currjson: any = "";
  amount: number = 1;
  changebase: string = "";
  tocountry: string = "";
  result: number = 1;

  createFormGroup() {
    return new FormGroup({
      amount: new FormControl(""),
      changebase: new FormControl(""),
      tocountry: new FormControl("")
    });
  }
  currencyForm: FormGroup;

  constructor(private currency: CurrencydataService) {
    this.currencyForm = this.createFormGroup();
  }

  ngOnInit() { }

  convert() {
    // 从表单中获取最新字段值
    const formValue = this.currencyForm.value;
    this.changebase = formValue.changebase;
    this.tocountry = formValue.tocountry;
    this.amount = Number(formValue.amount) || 1; // 处理空值或非数字情况

    this.currency
      .getcurrencydata(this.changebase)
      .subscribe({
        next: (data: any) => {
          this.currjson = data;
          this.result = this.currjson.rates[this.tocountry] * this.amount;
        },
        error: (err) => {
          console.error('请求失败:', err);
        }
      });
  }
}

内容的提问来源于stack exchange,提问作者alena love

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.13 01:35:26