Refining Data Fetching
I've been examining the user's need for server-side data prefetching in Angular Universal. I'm now exploring the optimal strategies for implementing data fetching that is effective and minimal in impact to the user's experience. This includes strategies for how to optimize data fetching to deliver a fast rendering and smooth user experience.
Assessing TransferState Usage
I'm now deeply considering the role of TransferState in conjunction with resolvers to streamline data transfer from the server to the client. The goal is to minimize re-fetching on the client-side, achieving this with a focus on Angular Universal's improved hydration capabilities. I'm evaluating how to best utilize resolvers in tandem with TransferState to streamline data handling and rendering times.
Devising Implementation Steps
I'm presently devising the steps to implement server-side data fetching. I've broken it down into prerequisites, service creation, resolver integration, and component consumption. My mental drafting involves utilizing HttpClient, TransferState, and makeStateKey within the service. The goal is efficient state transfer and streamlined rendering. I'm focusing on checking the transfer state for existing data and fetching new data only when needed, prioritizing server-side setting of the data when fetched.
Exploring Advanced Caching
I'm now integrating insights from Angular 16+ into my approach. The automatic HTTP client caching seems fantastic. However, I've re-evaluated and decided to include explicit TransferState usage, especially for understanding and advanced scenarios like POST requests. The focus is on implementing the resolver pattern, given it aligns directly with data prefetching needs for optimal rendering. I'm focusing on the introduction, the key service, and SSR enabling steps, refining the service to maximize performance.
Formulating Data Handling
I'm solidifying the steps for data handling. I'm building out a getData() method that checks transferState for existing data before fetching. I'm focusing on crafting a modern ResolveFn resolver and the component access pattern. I've confirmed that if using Angular 16+, provideClientHydration with withHttpTransferCache handles this automatically, which is the preferred and first approach I'll document.
Constructing Documentation Strategy
My focus is now on finalizing the documentation structure. I'm prioritizing two distinct methods: the efficient Angular 16+ approach using withHttpTransferCache, and the more manual Resolver and TransferState method, providing clear steps for both. I'm focusing on the conceptual explanation of server-side data embedding for the user. I'll include concise, commented code examples, and I'll conclude with verification instructions for users. I'm making sure to highlight the critical distinction between server-side fetching and state transfer.
Enhancing State Transfer
Currently, I'm concentrating on the TransferState implementation to solve the redundant client-side re-fetching. The solution necessitates TransferState to prevent duplicate calls, I'm making sure to highlight this critical need, which is essential to the user's experience. I'm focusing on the integration of TransferState to ensure data transfer efficiency.
Implementing server-side data prefetching in Angular Universal involves two distinct challenges:
- Fetching data on the server so the initial HTML contains the content (good for SEO and perceived performance).
- preventing the client from re-fetching that same data immediately after the page loads (Hydration).
Here are the two ways to handle this, depending on your Angular version.
Method 1: The Modern Way (Angular 16+)
Use: Automatic HTTP Transfer Cache
If you are using Angular 16 or newer with the standalone API, Angular handles this almost automatically using provideClientHydration with the Http Transfer Cache feature.
1. Setup app.config.ts
Ensure your application configuration includes client hydration and the HTTP transfer cache.
// app.config.ts
import { ApplicationConfig } from '@angular/core';
import { provideRouter } from '@angular/router';
import { provideHttpClient, withFetch } from '@angular/common/http';
import { provideClientHydration, withHttpTransferCache } from '@angular/platform-browser';
import { routes } from './app.routes';
export const appConfig: ApplicationConfig = {
providers: [
provideRouter(routes),
provideHttpClient(withFetch()), // 'withFetch' is recommended for SSR
provideClientHydration(
withHttpTransferCache() // <--- The Magic Line
)
]
};
2. Use a Standard Resolver
Create a straightforward resolver. You do not need to manually handle state transfer logic; Angular intercepts the HTTP request on the server, stores the result, and hands it to the client automatically.
// user.resolver.ts
import { inject } from '@angular/core';
import { ResolveFn } from '@angular/router';
import { HttpClient } from '@angular/common/http';
export const userResolver: ResolveFn<any> = (route, state) => {
const http = inject(HttpClient);
// The result of this GET will be cached & transferred automatically
return http.get('https://jsonplaceholder.typicode.com/users/1');
};
3. Update Routes
// app.routes.ts
import { Routes } from '@angular/router';
import { userResolver } from './user.resolver';
import { UserComponent } from './user/user.component';
export const routes: Routes = [
{
path: 'user',
component: UserComponent,
resolve: {
userData: userResolver
}
}
];
Method 2: The Manual Way (TransferState)
Use: Complex caching logic, non-GET requests, or Pre-Angular 16
If you need granular control (or are on an older version), use the TransferState service. This pattern involves checking if data exists in the "State" before making an HTTP call.
1. Create the Data Service with TransferState
This service ensures that if data was fetched on the server, the browser uses the cached version.
import { Injectable, Inject, PLATFORM_ID } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { TransferState, makeStateKey, StateKey } from '@angular/platform-browser';
import { isPlatformServer } from '@angular/common';
import { Observable, of, tap } from 'rxjs';
@Injectable({ providedIn: 'root' })
export class DataService {
// Create a unique key for the data
private DATA_KEY = makeStateKey<any>('user_data');
constructor(
private http: HttpClient,
private transferState: TransferState,
@Inject(PLATFORM_ID) private platformId: Object
) {}
getData(): Observable<any> {
// 1. Check if data exists in TransferState (Client-side check)
if (this.transferState.hasKey(this.DATA_KEY)) {
const storedData = this.transferState.get(this.DATA_KEY, null);
this.transferState.remove(this.DATA_KEY); // Optional: clear after use
return of(storedData);
}
// 2. If no data, fetch from API
return this.http.get('https://jsonplaceholder.typicode.com/users/1').pipe(
tap(data => {
// 3. If running on Server, start saving result to State
if (isPlatformServer(this.platformId)) {
this.transferState.set(this.DATA_KEY, data);
}
})
);
}
}
2. Create the Resolver
The resolver ensures the data is fetched before the route activates.
// data.resolver.ts
import { Injectable } from '@angular/core';
import { Resolve } from '@angular/router';
import { Observable } from 'rxjs';
import { DataService } from './data.service';
@Injectable({ providedIn: 'root' })
export class DataResolver implements Resolve<any> {
constructor(private dataService: DataService) {}
resolve(): Observable<any> {
// This calls the logic we wrote above.
// Server: Fetches API -> Saves to State -> Returns Data
// Client: Sees State -> Returns Data (Instant)
return this.dataService.getData();
}
}
3. Configure the Route
Attach the resolver to your route.
// app-routing.module.ts
import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { DataResolver } from './data.resolver';
import { UserComponent } from './user/user.component';
const routes: Routes = [
{
path: 'user',
component: UserComponent,
resolve: {
ssrData: DataResolver
}
}
];
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule { }
4. Consume in Component
The component retrieves the resolved data from the route snapshot, unaware of whether it came from the API or the cache.
// user.component.ts
import { Component, OnInit } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
@Component({
selector: 'app-user',
template: `
<h1>User Data</h1>
<pre>{{ data | json }}</pre>
`
})
export class UserComponent implements OnInit {
data: any;
constructor(private route: ActivatedRoute) {}
ngOnInit() {
// Data is ready immediately
this.data = this.route.snapshot.data['ssrData'];
}
}
How to Verify it works
- Build and Serve: Run
npm run dev:ssr (or npm run serve:ssr depending on your setup).
- Disable JavaScript (Optional but recommended): Go to your browser DevTools settings and disable JavaScript. Refresh the page.
- If you see the data, Server-Side Rendering is working.
- Enable JavaScript and Refresh:
- Open the Network Tab in DevTools.
- Refresh the page.
- Success Criteria: You should see the initial document request (Status 200) return the HTML with the data. You should NOT see a subsequent XHR/Fetch request to
jsonplaceholder.typicode.com.
- View Page Source:
- Right-click and "View Page Source".
- Scroll to the bottom. You should see a
<script id="ng-state"> tag containing your JSON data embedded in the HTML. This is the TransferState at work.