javascript - RxJS 中的多个异步字符串替换
问题描述
在 Angular 应用程序中,我有:
- 我想在其中翻译几个资源键的文本
- 一组资源键
("IS_LESS_THAN", "IS_GREATER_THAN", etc...)
- 一系列语言
("EN, NL, FR", etc..)
- 可以翻译单个资源键的服务。该服务有助于当所选语言发生更改时,它会通过可观察对象发出一个新值。
异步是复杂的部分。我不能使用 for 循环对文本执行简单的 string.replace() 操作,因为这只能以同步方式工作。
如何使用 RxJS 完成翻译?我有以下代码,但卡在最后:
const text = '....... 3 IS_LESS_THAN 5 ........';
const keys = ['IS_LESS_THAN', 'IS_GREATER_THAN', ....... ];
const translatedText$ = of(keys).pipe(
switchMap((key) =>
this.localizationService.translate(key).pipe( // Will update its value when the current language changes
map((value) => ({
// Store the original key/value combination to do the replace
key,
value,
}))
)
// PROBLEM: How to replace each key in the text and return the result?
// I tried reduce, but how to combine the accumulator and the value?
reduce((acc, val) => {
return val[0].replace(val[1], );
})
解决方案
您需要提供初始种子值,在您的情况下可能是text
.
reduce((translatedText, translation) => {
return translatedText.replace(translation.key, translation.value);
}, text)
如果您希望翻译所有密钥,您还应该考虑更改switchMap
为: https ://ncjamieson.com/avoiding-switchmap-related-bugs/mergeMap
推荐阅读
- php - docker-compose - Composer 在 /var/www/html 中找不到 composer.json 文件
- angular - angular 2材料表日期列混合字符串
- json - 如何使用 PowerShell 为 Azure 数据工厂 V2 数据集/管道获取有效的 JSON?
- c# - WPF过滤数据网格组合框列
- c# - 如何通过实体框架在 SQL 中授予用户 sys.admin 角色?
- r - 了解 lavaan 中的自由度
- python - pandas中不同元素的成对距离
- php - Google App Engine PHP 7.2 localhost 未使用我的入口点
- angular - Ionic 框架登录 API - 预检响应没有 HTTP ok 状态
- c# - 如何构造返回递归外键关系的实体框架查询