Transloco 将本地翻译对象与服务器端翻译对象合并

问题描述 投票:0回答:1

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

文档指出您可以使用

APP_INITIALIZER
提供程序设置翻译语言 https://ngneat.github.io/transloco/docs/recipes/prefetch

如果您只有静态 json 资源文件(例如

src/assets/i18n/en.json
),这可能会起作用,但我无法与从服务器获取的 json 翻译结合使用。

这是我使用应用程序初始化程序的尝试:

// 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 次,一半的时间我会看到服务器翻译,一半的时间会看到客户端翻译。

angular internationalization transloco
1个回答
0
投票

您可以尝试归还

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();
  }
}
© www.soinside.com 2019 - 2024. All rights reserved.