我有语言服务,可在我的应用程序中实现国际化。基本上,它在开发人员模式下也可以正常工作,在生产环境下sometimes
也可以工作。
我的问题是sometimes
的json文件的旧版本存储在浏览器中(如果我将以隐身模式打开网站,一切都按预期进行)。
我的json文件位于assets/i18n
目录下
language.service.ts:
import { HttpBackend, HttpClient } from '@angular/common/http';
import { Injectable, OnDestroy } from '@angular/core';
import { Subject } from 'rxjs/internal/Subject';
import { Subscription } from 'rxjs/internal/Subscription';
@Injectable({
providedIn: 'root'
})
export class LanguageService implements OnDestroy {
activeLanguage: string = 'ka';
data: any = {};
data$: Subject<any>;
dataSubscription: Subscription = new Subscription();
constructor(
private httpClient: HttpClient,
private httpBackend: HttpBackend
) {
this.data$ = new Subject();
this.httpClient = new HttpClient(httpBackend);
}
loadLanguageFile(lang: string): void {
if (lang) {
this.activeLanguage = lang;
}
const path = `../assets/i18n/${this.activeLanguage}.json`;
if (this.data[this.activeLanguage]) {
this.data$.next(this.data[this.activeLanguage]);
} else {
this.dataSubscription = this.httpClient.get(path).subscribe(res => {
this.data[this.activeLanguage] = res;
this.data$.next(this.data[this.activeLanguage]);
});
}
}
ngOnDestroy(): void {
this.dataSubscription.unsubscribe();
}
}
language.module.ts:
import { APP_INITIALIZER, NgModule } from '@angular/core';
import { LanguageService } from './language.service';
@NgModule({
imports: [],
exports: [],
declarations: [],
providers: [
{
provide: APP_INITIALIZER,
multi: true,
deps: [LanguageService],
useFactory: (language: LanguageService) => () => {
return language.loadLanguageFile('ka');
}
}
]
})
export class LanguageModule {}
translate.pipe.ts:
import { OnDestroy, Pipe, PipeTransform } from '@angular/core';
import { LanguageService } from '@app/core/services/language/language.service';
import { Subscription } from 'rxjs/internal/Subscription';
@Pipe({
name: 'translate',
pure: false
})
export class TranslatePipe implements PipeTransform, OnDestroy {
data: any;
subscription: Subscription = new Subscription();
constructor(private languageService: LanguageService) {
this.subscription = this.languageService.data$.subscribe(res => {
this.data = res;
});
}
transform(key: string): string {
this.data = this.languageService.data[this.languageService.activeLanguage];
return this.data && this.data[key] ? this.data[key] : key;
}
ngOnDestroy(): void {
this.subscription.unsubscribe();
}
}
示例用例:
<div>{{ text | translate }}</div>
我该怎么办?