i18n文件在生产中缓存

时间:2019-02-23 10:03:54

标签: angular internationalization

我有语言服务,可在我的应用程序中实现国际化。基本上,它在开发人员模式下也可以正常工作,在生产环境下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>

我该怎么办?

0 个答案:

没有答案