Using HTTP transfer cache, we can reuse the data fetched during server-side rendering on the client, eliminating duplicate requests.
// app.config.ts
export const appConfig: ApplicationConfig = {
providers: [
provideHttpClient(
withFetch()
),
provideClientHydration(
withHttpTransferCacheOptions({
includePostRequests: true
})
)
]
};
// The same API call is now cached
this.api.getCards().subscribe(cards => {
this.cards = cards;
});
Watch the network tab and console. Notice how the data is only fetched once during SSR and reused on the client.
{
"totalCards": 20,
"firstCard": {
"id": 1,
"title": "Deserunt nemo et vel.",
"imageUrl": "https://picsum.photos/400/300?random=1"
},
"lastCard": {
"id": 20,
"title": "Vitae totam labore iste est.",
"imageUrl": "https://picsum.photos/400/300?random=20"
},
"timestamp": "2024-11-06T19:56:56.721Z"
}