You need to enable JavaScript to run this app. ngx-translate调用setTranslation编译阿拉伯语翻译触发SyntaxError的问题
优惠活动
大模型
产品
解决方案
定价
更多

ngx-translate调用setTranslation编译阿拉伯语翻译触发SyntaxError的问题

setTranslations(lang, translations) 方法编译阿拉伯语翻译是否存在已知问题?

技术栈版本信息

  • 依赖版本:@ngx-translate/core@12.0.0
  • Angular版本:10.0.8

复现场景

站点共配置6种语言的JSON格式翻译资源(德语de、英语en、西班牙语es、意大利语it、法语fr、阿拉伯语ar),通过HttpClient加载供ngx-translate库使用。所有语言包结构完全一致,仅翻译内容值存在差异,且均可通过TranslateService.getTranslations()方法正常读取。

语言切换的核心执行逻辑如下:

changeLocale(locale: 'de' | 'en' | 'it' | 'es' | 'fr' | 'ar'): void {
  this.identityService.changeLocale(locale).subscribe({
    next: () => {
      this.translate.getTranslation(locale).subscribe((translations) =>{
        console.log(locale, translations) // 输出当前locale及对应翻译对象
        try{
          this.translate.setTranslation(locale, translations) // 为指定locale设置翻译资源
          console.log("Set translation!")
          this.translate.use(locale)
          console.log("Used translation!")
        } catch (e) {
          console.error(e)
        }
      })
    },
    error: (error) => this.messageService.processError(error)
  });
}

其余5种语言执行上述流程时完全符合预期:翻译资源可正常设置并通过this.translate.use(locale)生效。唯独加载阿拉伯语时,在setTranslation调用环节抛出以下解析错误:

SyntaxError: Expected "," or "}" but "ا" found.
    at Xt (parser.js:407)
    at parse (parser.js:1978)
    at t.value (compiler.js:39)
    at t.value (compiler.js:46)
    at t.value (compiler.js:46)
    at t.value (compiler.js:46)
    at t.value (compiler.js:46)
    at t.value (messageformat.js:385)
    at TranslateMessageFormatCompiler.compileTranslations (translate-message-format-compiler.ts:56)
    at TranslateService.setTranslation (translate.service.ts:282)
    at SafeSubscriber._next (navbar.component.ts:128)
    at SafeSubscriber.__tryOrUnsub (Subscriber.ts:265)
    at SafeSubscriber.next (Subscriber.ts:207)
    at Subscriber._next (Subscriber.ts:139)
    at Subscriber.next (Subscriber.ts:99)
    at TakeSubscriber._next (take.ts:92)
    at TakeSubscriber.next (Subscriber.ts:99)
    at ReplaySubject._subscribe (ReplaySubject.ts:80)
    at ReplaySubject._trySubscribe (Observable.ts:238)
    at ReplaySubject._trySubscribe (Subject.ts:116)
    at ReplaySubject.subscribe (Observable.ts:219)
    at TakeSubscriber.shareReplayOperation (shareReplay.ts:112)
    at AnonymousSubject.subscribe (Observable.ts:214)
    at TakeOperator.call (take.ts:72)
    at AnonymousSubject.subscribe (Observable.ts:214)
    at Object.next (navbar.component.ts:125)
    at SafeSubscriber.__tryOrUnsub (Subscriber.ts:265)
    at SafeSubscriber.next (Subscriber.ts:207)
    at Subscriber._next (Subscriber.ts:139)
    at Subscriber.next (Subscriber.ts:99)
    at MapSubscriber._next (map.ts:89)
    at MapSubscriber.next (Subscriber.ts:99)
    at FilterSubscriber._next (filter.ts:101)
    at FilterSubscriber.next (Subscriber.ts:99)
    at MergeMapSubscriber.notifyNext (mergeMap.ts:162)
    at SimpleInnerSubscriber._next (innerSubscribe.ts:30)
    at SimpleInnerSubscriber.next (Subscriber.ts:99)
    at XMLHttpRequest.onLoad (xhr.ts:214)
    at XMLHttpRequest.sentryWrapped (helpers.ts:85)
    at ZoneDelegate.invokeTask (zone.js:421)
    at Object.onInvokeTask (core.js:27136)
    at ZoneDelegate.invokeTask (zone.js:420)
    at Zone.runTask (zone.js:188)
    at ZoneTask.invokeTask [as invoke] (zone.js:503)
    at invokeTask (zone.js:1671)
    at XMLHttpRequest.globalZoneAwareCallback (zone.js:1708)

问题根因

该报错不属于setTranslation方法本身的逻辑缺陷,是ngx-translate 12版本默认集成的TranslateMessageFormatCompiler的已知适配问题:
该编译器底层依赖的旧版messageformat.js解析器,字符识别逻辑存在缺陷,解析阿拉伯语文本时,会错误将阿拉伯语首字母ا识别为消息格式语法的分隔标记,触发语法解析异常。其余5种语言的文本均使用拉丁字母,不会触发该识别逻辑,因此仅阿拉伯语场景会复现报错。

解决方案

  • 替换默认翻译编译器,跳过messageformat语法解析。如果项目不需要使用复数、动态占位符等messageformat高级语法,可直接自定义编译器,返回原始翻译文本,从根源避开解析器的字符识别bug,且不影响其余5种语言的正常加载。示例实现:
    import { TranslateCompiler } from '@ngx-translate/core';
    
    // 纯文本透传编译器
    class PlainTranslationCompiler implements TranslateCompiler {
      compile(value: string, lang: string): string {
        return value;
      }
      compileTranslations(translations: Record<string, unknown>, lang: string): Record<string, unknown> {
        return translations;
      }
    }
    
    // 在应用根模块的providers中注入替换
    providers: [
      { provide: TranslateCompiler, useClass: PlainTranslationCompiler }
    ]
    
  • 保留messageformat高级语法能力的场景,可按照解析器的转义规则对阿拉伯语翻译文本做特殊字符转义,将包含被误判字符的翻译值用单引号包裹,明确告知解析器该段为纯文本,无需做语法规则匹配。
  • 在版本兼容范围内升级@ngx-translate/messageformat及底层messageformat.js依赖到已修复阿拉伯语适配问题的版本,注意匹配Angular10、ngx-translate 12的版本兼容边界,避免引入版本冲突。

预期效果

调整完成后,阿拉伯语翻译对象可与其余语言翻译资源保持一致的加载流程,正常完成编译、加载与切换生效。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.11.04 09:06:04