我正在寻找一种稳健的方法来从服务器预取翻译文件,并在应用程序初始化期间与本地翻译文件合并.

文档指出,您可以使用APP_INITIALIZER提供程序设置翻译语言 https://ngneat.github.io/transloco/docs/recipes/prefetch

如果你只有一个静态的json资源文件(例如src/assets/i18n/en.json),这可能会起作用,但是我不能把这个工作与从服务器获取的json翻译结合起来.

下面是我使用app initializer的try :

// app.module.ts 
...
    {
      provide: APP_INITIALIZER,
      multi: true,
      useFactory: preloadServer,
      deps: [TranslocoService, HttpClient]
    }
...
export function preloadUser(transloco: TranslocoService, _httpClient: HttpClient) {
  return () => {
    combineLatest([
      _httpClient.get(`http://my.server.com/en.json`), // fetches a remote translation
      transloco.selectTranslation('en') // fetches the local static asset file
    ]).pipe(
      take(1),
      map(([server, client]) => (
        Object.assign(client, server) // Merges the 2 objects
      )),
      tap(merged => transloco.setTranslation(merged, 'en')) // Updates the 'en' translation with the merged object
    ).toPromise();
  }
}

奇怪的是,这是随机起作用的.如果我重新加载应用程序10次,一半的时间我会看到服务器翻译,一半的时间我会看到客户端翻译.

Update

在@Naren-Murali的S回答之后,我意识到我可以重写应用程序初始化器函数来利用TransLoco API,它提供了一个翻译合并选项,所以我添加了我的更新方法

export function preloadTranslation(transloco: TranslocoService, httpClient: HttpClient) {
  return () => {
    return concat(
      transloco.selectTranslation('en'), // This fetches the local translation
      httpClient.get(`http://my.server.com/en.json`) // This fetches the server translation
    ).pipe(
      // Merge the server keys into the local object using the transloco API option "{ merge: true }"
      tap(serverTranslation => transloco.setTranslation(serverTranslation, 'en', { merge: true }))
    ).toPromise();
  }
}

推荐答案

你能试着把那combineLatest元归还吗?也许这就是遗失的东西!

export function preloadUser(transloco: TranslocoService, _httpClient: HttpClient) {
  return () => {
    return combineLatest([ //                        <-- changed here!
      _httpClient.get(`http://my.server.com/en.json`), // fetches a remote translation
      transloco.selectTranslation('en') // fetches the local static asset file
    ]).pipe(
      take(1),
      map(([server, client]) => (
        Object.assign(client, server) // Merges the 2 objects
      )),
      tap(merged => transloco.setTranslation(merged, 'en')) // Updates the 'en' translation with the merged object
    ).toPromise();
  }
}

Angular相关问答推荐

无法绑定到ngIf,因为它不是dis angular 17的已知属性

Angular 信号不更新afterNextender()

带有两个注入服务的函数式解析器(Angular 15)

带有服务依赖的Angular测试类

如何在构造函数中测试MatDialog.Open

独立组件;依赖项注入

Angular 17:在MouseOver事件上 Select 子组件的正确ElementRef

Sass-Loader中出现分号错误:ANGLE应用程序的缩进语法中不允许使用分号

VS代码中带Angular 17的缩进新控制流

合并Cypress和Karma的代码覆盖率报告JSON文件不会产生正确的结果

Angular CLI 与 Angular 版本不兼容

Angular *ngIf 表达式中这么多冒号的作用是什么?

如何在Angular2中基于特定的构建环境注入不同的服务?

Angular 5 中服务的生命周期是什么

如何在 Angular 2 中获取与 ElementRef 关联的组件的引用

Error: Module not found: Error: Can't resolve '@angular/cdk/scrolling'

Angular-CLI 代理到后端不起作用

Angular 2 单元测试 - @ViewChild 未定义

样式 html,来自 Web 组件的正文

找不到@angular/common/http模块