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

Angular项目中TypeScript映射接口响应时如何去除< >特殊符号

实现方案

步骤1:定义通用字符清理函数

// 全局替换所有<和>符号为空
const stripAngleBrackets = (str: string): string => str.replace(/[<>]/g, '');

步骤2:修改接口请求的响应处理逻辑

使用Object.fromEntries的简洁写法(需要ES2019及以上运行环境支持):

return this.http.get(this.url)
  .toPromise()
  .then((response: unknown) => {
    const rawList = response as IValueSetDictionary[];
    return rawList.map(rawItem => ({
      valueSet: Object.fromEntries(
        Object.entries(rawItem.valueSet)
          .map(([key, value]) => [
            stripAngleBrackets(key),
            stripAngleBrackets(value as string)
          ])
      )
    } as IValueSetDictionary));
  })
  .catch(this.handleError);

如果需要兼容低版本环境,可以用forEach遍历实现:

return this.http.get(this.url)
  .toPromise()
  .then((response: unknown) => {
    const rawList = response as IValueSetDictionary[];
    return rawList.map(rawItem => {
      const processed: Record<string, string> = {};
      Object.entries(rawItem.valueSet).forEach(([key, value]) => {
        processed[stripAngleBrackets(key)] = stripAngleBrackets(value as string);
      });
      return { valueSet: processed } as IValueSetDictionary;
    });
  })
  .catch(this.handleError);

可选优化:完善接口类型定义

可以把原来的valueSet字段类型改为更明确的键值对类型,提升类型安全性:

export interface IValueSetDictionary {
  valueSet: Record<string, string>;
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 16:06:04