如何修复我的 ssr Angular 15 应用程序的国际化延迟?

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

我有一个 Angular 15 应用程序,我设置了

internationalization i18n
并且效果很好。我的应用程序不大,只有 2 页。现在,当我将 SSR 添加到我的应用程序时,我遇到了一些翻译问题,但它只能在生产中看到(在本地主机上我无法观察到这个问题),所以当我的页面加载到我使用翻译的地方时,我首先得到像
translation.title
这样的路径,2-3秒后我得到了文本。Example 1example after page load

我创建了一个翻译拦截器

@Injectable()
export class TranslateInterceptor implements HttpInterceptor {
  private readonly DEFAULT_PORT = 4000;
  // @ts-ignore
  private readonly PORT = process.env.PORT || this.DEFAULT_PORT;

  constructor(@Inject(REQUEST) private request: express.Request) {
  }

  getBaseUrl(req: express.Request) {
    const { protocol, hostname } = req;
    return this.PORT ?
      `${protocol}://${hostname}:${this.PORT}` :
      `${protocol}://${hostname}`;
  }

  intercept(request: HttpRequest<any>, next: HttpHandler) {
    if (request.url.startsWith('./assets')) {
      const baseUrl = this.getBaseUrl(this.request);
      request = request.clone({
        withCredentials: true,
        url: `${baseUrl}/${request.url.replace('./assets', 'assets')}`,
      });
    }
    return next.handle(request);
  }
}

我在应用程序模块中添加:

export function HttpLoaderFactory(http: HttpClient) {
  return new TranslateHttpLoader(http, './assets/i18n/', '.json');
}

    TranslateModule.forRoot({
      loader: {
        provide: TranslateLoader,
        useFactory: HttpLoaderFactory,
        deps: [HttpClient],
      },
    }),

并在应用程序组件中使用它,例如:

  constructor(readonly appService: AppService, private router: Router, private translate: TranslateService) {
    this.translate.setDefaultLang('en');
    this.translate.use('en');
  }
angular internationalization ngx-translate
© www.soinside.com 2019 - 2024. All rights reserved.