首页 > 解决方案 > RxJS 中的多个异步字符串替换

问题描述

在 Angular 应用程序中,我有:

异步是复杂的部分。我不能使用 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], );
        })

标签: javascriptangulartypescriptrxjs

解决方案


您需要提供初始种子值,在您的情况下可能是text.

reduce((translatedText, translation) => {
  return translatedText.replace(translation.key, translation.value);
}, text)

如果您希望翻译所有密钥,您还应该考虑更改switchMap为: https ://ncjamieson.com/avoiding-switchmap-related-bugs/mergeMap


推荐阅读