Angular Universal TransferHttpCacheModule 无法在路由器导航的路线内工作,仅在重新加载后

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

我有一个通用应用程序,其中

TransferHttpCacheModule
添加到
app.module.ts
,如下所示:

@NgModule({
  ...
  imports: [
    BrowserModule,
    TransferHttpCacheModule,
    AppRoutingModule,
  ],
  providers: [{ provide: APP_ID, useValue: 'serverApp' }],
  bootstrap: [AppComponent],
})
export class AppModule {}

路线实施:

const routes: Routes = [
  { path: 'first-component', component: FirstComponent },
  { path: 'ssr-test', component: HttpExampleComponent },
  ...
];

app.component.html
中,我添加了一个导航链接以到达
ssr-test
路径

    <li>
      <a
        routerLink="/ssr-test"
        routerLinkActive="activebutton"
        ariaCurrentWhenActive="page"
        >SSR test</a
      >
    </li>

HttpExampleComponent
模板包含一个
<app-list></app-list>
子级,它对组件初始化执行
GET
调用:

export class ListComponent implements OnInit {
  list?: Products[];

  constructor(private apiClient: ApiClientService) {}

  ngOnInit(): void {
    this.loadList();
  }

  loadList(): void {
    this.apiClient.getList().subscribe((data) => {
      console.log('data', data);
      this.list = data;
    });
  }
  ...
}

当我导航到

ssr-path
路线时,页面显示正确,但页面源中不存在
<script id="serverApp-state" type="application/json">
标签,并且执行
GET
调用

如果我重新加载页面,则存在

<script>
并且不执行
GET
调用,但我希望数据在不重新加载页面的情况下存在,并且不执行
GET
调用

我错过了什么吗?

angular server-side-rendering angular-universal angular-httpclient angular-transfer-state
1个回答
0
投票

这是预期的行为。

TransferHttpCacheModule
安装一个 Http 拦截器,可避免客户端上重复的
HttpClient
GET 请求,以应对在服务器端呈现应用程序时已发出的请求。

在应用程序稳定之前都是如此:

  constructor(appRef: ApplicationRef, private transferState: TransferState) {
    // Stop using the cache if the application has stabilized, indicating initial rendering is
    // complete.
    appRef.isStable
      .pipe(
        filter((isStable) => isStable),
        take(1),
        tap(() => (this.isCacheActive = false)),
      )
      .subscribe();
  }

源码中的transfer-http-cache.interceptor.ts

© www.soinside.com 2019 - 2024. All rights reserved.