首页 > 解决方案 > Angular Transferstate 预渲染了两次 - html 中的 2 个 app-state 脚本标签和 2x 由 Angular 注释预渲染

问题描述

我正在使用预渲染运行 Angular Universal。预渲染时,我得到 2 个 Angular 预渲染脚本标签,但并非总是如此。在我的开发环境中,我预渲染了 10 条路由,并且 10 次中有 7 次有 2 个应用程序状态脚本标签。在生产环境中,它一直在发生,因此不会出现仅 1 个脚本标签。

<script id="app-state" type="application/json">{}</script>
<script id="app-state" type="application/json">{&q;vacancy-asd6rIXJox&q;:{&q; ... <7script>

和 2 倍的评论“由 Angular 预先呈现:

... </script></body>
<!-- This page was prerendered with Angular Universal -->
<!-- This page was prerendered with Angular Universal --></html

这是我来自 angular.json 的预渲染配置

 "prerender": {
          "builder": "@nguniversal/builders:prerender",
          "options": {
            "browserTarget": "app:build:ci",
            "serverTarget": "app:server:ci",
            "routes": [
              "/"
            ],
            "routesFile": "routes.txt"
          },
          "configurations": {
            "production": {}
          }
        },

我通过调用开始预渲染npx ng run app:prerender

这是我的服务中调用 TransferState 的代码:

 async requestVacancy( uuid: string ): Promise<PublicVacancy> {
    const stateKey = this.getVacancyStateKey( uuid );

    const queryString = environment.restApiUrl + '/publicVacancy/' + uuid;
    const vacancy = await this.http.get<any>( queryString ).toPromise();

    this.transferState.set( stateKey, vacancy );
    return vacancy;
  }

  async getVacancy( uuid: string ): Promise<PublicVacancy> {
    const statekey = this.getVacancyStateKey( uuid );
    if ( this.transferState.hasKey( statekey ) ) {
      return this.transferState.get<PublicVacancy>( statekey, {} as PublicVacancy );
    }
    return (await this.requestVacancy( uuid ));
  }

在我的 appModule 中导入“BrowserTransferStateModule”,在我的 appServermodule 中导入“ServerTransferStateModule”作为未更改。

鉴于此,有关此预渲染如何发生两次的任何想法?我一直在寻找这个错误很长一段时间,但我无法弄清楚。

标签: angularangular-universalprerenderangular-transfer-state

解决方案


我已将此作为错误报告发布在 Angular: https ://github.com/angular/universal/issues/2334#event-5393577965

当我发布它时,他们已经解决了这个问题。

我必须升级到"@nguniversal/builders": "^12.1.1",然后解决问题


推荐阅读