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

如何在指定URL中添加API key?Angular Service请求URL出现%22问题求解

问题原因

%22是双引号的URL编码形式,你的问题出在查询参数拼接逻辑的两处错误:

  • 模板字符串中多余的手写双引号,这些双引号会被直接拼入URL,编码后就出现了%22
  • 不同查询参数之间没有加分隔符&,参数拼接逻辑错误

修复方法

将你代码中HTTP请求的参数拼接部分替换为以下写法即可,注意如果datePeriodURLString末尾已经带?,则把下面的?换成&即可:

await this.HTTPReq("GET",this.exchangeAPI,`${datePeriodURLString}?access_key=${this.key}&base=${this.baseCurrency.active}`).then((res)=>{
// 后续原有逻辑保持不变

进阶优化建议

推荐使用Angular官方提供的HttpParams来构建查询参数,无需手动处理分隔符、编码问题,稳定性更高,同时你原有代码中额外嵌套的Promise属于冗余逻辑,async方法本身就会返回Promise,可以直接简化写法:

// 先引入HttpParams
import { HttpParams } from '@angular/common/http';

async getCurrencies() {
    this.formatValidTimePeriod()
    this.statusService.sendStatus('updateStarted')
    let datePeriodURLString = this.formatDatePeriodURLString()
    // 自动处理参数拼接和编码
    let params = new HttpParams({fromString: datePeriodURLString})
      .set('access_key', this.key)
      .set('base', this.baseCurrency.active)
    const res = await this.HTTPReq("GET", this.exchangeAPI, params)
    let rates=res.rates
    if (this.baseCurrency.dropDownList.length < 1) {
      this.setCurrencyDropDownList(rates)
    }
    if (!this.currencies.selected.active) {
      this.currencies.list = rates;
    } else {
      this.setPricesForSelectedCurrency(rates)
    }
    this.statusService.sendStatus('updateFinished')
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 10:09:05