Angular中如何处理API返回文本的Unicode字符显示问题
解决Angular中[innerHTML]绑定Unicode转义字符不显示的问题
问题核心:API返回的文本里的\u2022这类Unicode转义序列是字符串形式,Angular的[innerHTML]不会自动解析它们,所以直接显示成了\u2022而不是项目符号•。
解决方案:自定义管道解码Unicode转义字符
创建一个Angular管道来处理字符串中的Unicode转义,把\uXXXX格式的转义序列转换成对应的实际字符。
1. 生成自定义管道
在项目里执行命令创建管道:
ng generate pipe decode-unicode
2. 实现管道逻辑
修改decode-unicode.pipe.ts的代码:
import { Pipe, PipeTransform } from '@angular/core'; @Pipe({ name: 'decodeUnicode' }) export class DecodeUnicodePipe implements PipeTransform { transform(value: string): string { if (!value) return value; // 匹配所有\uXXXX格式的转义序列 return value.replace(/\\u([0-9a-fA-F]{4})/g, (match, hex) => { // 把十六进制字符串转换成十进制,再转成Unicode字符 return String.fromCharCode(parseInt(hex, 16)); }); } }
3. 在模板中使用管道
修改你的HTML模板,让[innerHTML]绑定经过管道处理后的文本:
<div [innerHTML]="agreementData.text | decodeUnicode"></div>
额外注意:HTML安全
如果API返回的HTML内容不可信,建议结合Angular的DomSanitizer来避免XSS风险,修改管道加入安全处理:
import { Pipe, PipeTransform } from '@angular/core'; import { DomSanitizer, SafeHtml } from '@angular/platform-browser'; @Pipe({ name: 'decodeUnicode' }) export class DecodeUnicodePipe implements PipeTransform { constructor(private sanitizer: DomSanitizer) {} transform(value: string): SafeHtml { if (!value) return value; const decoded = value.replace(/\\u([0-9a-fA-F]{4})/g, (match, hex) => { return String.fromCharCode(parseInt(hex, 16)); }); // 返回安全的HTML内容 return this.sanitizer.bypassSecurityTrustHtml(decoded); } }
这样处理后,\u2022就会被正确解析成•符号,同时也能保留原有的HTML标签结构。
内容的提问来源于stack exchange,提问作者Tobias Foxtrot
相关产品推荐
相关产品推荐

