如何检查translate.instant的返回值是否被翻译一次

How to check if the returned value of translate.instant is translated once

使用ngx-translate,我写了这个函数,我想做的是

接口 IWidgetFilterValue = { 标签:字符串; 值:字符串; }

getSortedOptions(filterOptionsArr: IWidgetFilterValue[]): IWidgetFilterValue[] {
    const filterOptionsArrNew = [...filterOptionsArr];
    return filterOptionsArrNew.sort((a: IWidgetFilterValue, b: IWidgetFilterValue): number => {
      this.translateService
      const aTranslated =
        (a && a.key && this.translateService.instant(a.key)) || (a && a.value) || '';
      const bTranslated =
        (b && b.key && this.translateService.instant(b.key)) || (b && b.value) || '';

      return aTranslated.localeCompare(bTranslated);
    });
  }

现在我期待的是,如果 a.key 或 b.key 没有得到正确的翻译文本,那么我想 return a.value 或 b.value, 这是问题 this.translateService.instant 方法将 return 翻译的文本(如果可用)或者它将 return identifier/key 值,

这意味着我永远不会得到 a.value/b.value 根据上面的函数

var a = {"label":"Approved in english","key":"30349a66-1f39-412e-a841-052890516b2a","value":"Approved in english"}

this.translateService.instant(a.key);
"Approved in english"    //CORRECT

a.key; // "30349a66-1f39-412e-a841-052890516b2a"
a.key = a.key+'11111111111';  // NOW changed the key, such that I should not get the translation
"30349a66-1f39-412e-a841-052890516b2a11111111111"

this.translateService.instant(a.key);
"30349a66-1f39-412e-a841-052890516b2a11111111111" // So translateService.instant will return some value when the key passed to it is a truthy

但是我想要的是,如果我没有为传递的密钥翻译文本,我想 return a.value/b.value

我可以想到一个解决方案,如果 this.translateService.instant(a.key) 的 return 值是特定的正则表达式模式并且是这种格式,那么这意味着我没有得到翻译文本,那么我可以考虑换a.value/b.value

喜欢

private isTranslatedTextFound(a) { 
  const trans = this.translateService.instant(a.key);
// reg_exp look like for this pattern [a-z0-9]{8}-[a-z0-9]{4}-[a-z0-9]{4}-[a-z0-9]{4}-[a-z0-9]{12}
  if(//check trans against regexp){ 

      return a.value
  }else{
     return trans;
 }
  
}

getSortedOptions(filterOptionsArr: IWidgetFilterValue[]): IWidgetFilterValue[] {
    const filterOptionsArrNew = [...filterOptionsArr];
    return filterOptionsArrNew.sort((a: IWidgetFilterValue, b: IWidgetFilterValue): number => {
      this.translateService
      const aTranslated =
        (a && a.key && a.value && this.isTranslatedTextFound(a) || '';
      const bTranslated =
        (b && b.key && b.value && this.isTranslatedTextFound(b) || '';
      return aTranslated.localeCompare(bTranslated);
    });
  }

是否有其他正确的方法来解决这个问题

我认为解决方案隐藏在您的问题中。

here is the problem this.translateService.instant method will return translated text if it is available or it will return the identifier/key value

您可以将您从 translateService 获得的内容与您的密钥进行比较,如果相同,您可以 return a.value.

private isTranslatedTextFound(a) { 
  const trans = this.translateService.instant(a.key);
  return trans === a.key ? a.value : trans;
}