【问题标题】:ngx-translate - Translate items synchronouslyngx-translate - 同步翻译项目
【发布时间】:2023-02-04 06:01:30
【问题描述】:

我有一个组件,它采用 MenuItem 对象数组:

<p-contextMenu [model]="contextMenuItems"></p-contextMenu>

我在函数中创建这些菜单项:

private createContextMenuItems(): MenuItem[] {
    let menuItems: MenuItem[] = [
      {
        id: 'play',
        label: 'Play'
        icon: 'pi pi-play',
      },
...
doSomeAdditionalWork(menuItems);
return menuItems;

完成后,我对这些菜单项进行一些额外的处理,并设置 this.menuItems = this.createContextMenuItems() 来填充组件。

我遇到的问题是翻译服务是异步的:

this.translate.get('VOICEMAIL_INBOX.PLAY_VIEW').subscribe()

我不确定如何设置它,以便它在执行其他工作之前进行转换,并将 MenuItem[] 的集合返回给调用者以绑定到组件。我考虑过使整个链异步并使用await firstValueFrom()之类的东西并同步处理这些,但这需要我将整个调用链着色为async而且我仍然不确定如何在绑定之前等待它解析翻译组件。

ngx-translate 确实有一个 instant() 方法。但是,这只会在我使用它时返回密钥,而不是翻译后的值。

【问题讨论】:

    标签: angular asynchronous ngx-translate


    【解决方案1】:

    根据我的经验,你永远不想反对异步行为,而是拥抱它。我发现这个 site 是一个有用的资源,可以确定在各种情况下我需要哪种异步函数。为此,我相信您可以将 forkJoin 与地图结合使用。请看这个stackblitz example。这里的要点如下:

    在父组件 html 中:

    <app-child [menu]="menu | async"></app-child>
    

    在父组件ts中:

    this.buildMenu();
    this.translate.onLangChange.subscribe(() => this.buildMenu());
    

    和:

    private buildMenu(): void {
    this.menu = forkJoin([
      this.translate.get('VOICEMAIL_INBOX.PLAY_VIEW'),
      this.translate.get('VOICEMAIL_INBOX.DELETE'),
    ]).pipe(
      map(([playTranslation, deleteTranslation]) => {
        const playMenu = {
          id: 'play',
          label: playTranslation,
          icon: 'pi pi-play',
        };
        const deleteMenu = {
          id: 'delete',
          label: deleteTranslation,
          icon: 'pi pi-delete',
        };
        return [playMenu, deleteMenu];
      })
    );
    

    }

    在子组件 html 中:

    <div *ngFor="let menuItem of menu">
      <h2>{{ menuItem.label }}</h2>
    </div>
    

    在子组件ts中:

    @Input() menu: any[];
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-06-23
      • 2019-02-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多