我正在寻找一种稳健的方法来从服务器预取翻译文件,并在应用程序初始化期间与本地翻译文件合并.
文档指出,您可以使用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();
}
}