首页 > 解决方案 > Spartacus Storefront 多站点 I18n 与后端

问题描述

在进行 I18n 时,我们的 MultiSite Spartacus 设置遇到了一些问题。

  1. 我们希望为每个站点提供不同的翻译,因此我们将它们放在一个 API 上,该 API 可以返回依赖于 baseSite 的消息,例如:backend.org/baseSiteX/messages?group=common
    但是 Spartacus 设置不允许我们通过 baseSite?我们可以通过{{lng}}and {{ns}},但不能通过 baseSite。
    请参阅https://sap.github.io/spartacus-docs/i18n/#lazy-loading 我们可以通过覆盖i18nextInit来做到这一点,但我不确定如何实现这一点。

  2. 在文档中,它说您可以crossOrigin: true在配置中使用,但这似乎不起作用。类型检查说它不受支持,它仍然显示 uw CORS 问题

有人对这些问题有想法吗?

标签: internationalizationspartacus-storefronti18next-http-backend

解决方案


目前仅支持语言 {{lng}} 和块名称 {{ns}} 作为i18n.backend.loadPath配置中的动态参数。

为了实现您的目标,您可以实现自定义 Spartacus以根据以下值CONFIG_INITIALIZER填充您的配置:i18n.backend.loadPathBaseSiteService.getActive()

@Injectable({ providedIn: 'root' })
export class I18nBackendPathConfigInitializer implements ConfigInitializer {
  readonly scopes = ['i18n.backend.loadPath']; // declare config key that you will resolve
  readonly configFactory = () => this.resolveConfig().toPromise();

  constructor(protected baseSiteService: BaseSiteService) {}

  protected resolveConfig(): Observable<I18nConfig> {
    return this.baseSiteService.getActive().pipe(
      take(1),
      map((baseSite) => ({
        i18n: {
          backend: {
            // initialize your i18n backend path using the basesite value:
            loadPath: `https://backend.org/${baseSite}/messages?lang={{lng}}&group={{ns}}`,
          },
        },
      }))
    );
  }
}

并在您的模块中提供它(即在 app.module 中):

@NgModule({
  providers: [
    {
      provide: CONFIG_INITIALIZER,
      useExisting: I18nBackendPathConfigInitializer,
      multi: true,
    },
  ],
  /* ... */
})

注意:上述解决方案假定活动基站仅在应用启动时设置一次(默认情况下在 Spartacus 中就是这种情况)。


推荐阅读