Performance: TransferState for data sharing
TransferState affects the initial page load speed by reducing duplicate HTTP requests between server and client.
Jump into concepts and practice - no test required
constructor(private transferState: TransferState, private http: HttpClient) {}
ngOnInit() {
const saved = this.transferState.get(DATA_KEY, null);
if (saved !== null) {
this.data = saved;
this.transferState.remove(DATA_KEY);
} else {
this.http.get('/api/data').subscribe(data => {
this.data = data;
this.transferState.set(DATA_KEY, data);
});
}
}ngOnInit() {
this.http.get('/api/data').subscribe(data => this.data = data);
}| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| Duplicate HTTP fetch on server and client | Minimal | 1 reflow after data loads | Medium paint cost due to delayed content | [X] Bad |
| Using TransferState to share data | Minimal | Single reflow on server render | Lower paint cost due to faster content display | [OK] Good |
TransferState service?makeStateKey in Angular?makeStateKey function to create keys, not a constructor or other function.makeStateKey correctly with proper syntax.const USER_KEY = makeStateKey('user');
this.transferState.set(USER_KEY, { name: 'Alice', age: 30 });What will this.transferState.get(USER_KEY, null) return on the client?set is serialized and available on the client.get with the same key returns the stored object, not null or error.const DATA_KEY = makeStateKey('data');
this.transferState.set(DATA_KEY, { value: 42 });
const data = this.transferState.get('DATA_KEY', null);get method requires the same StateKey object used in set, not a string.transferState.set(PRODUCTS_KEY, products). On client, retrieve with transferState.get(PRODUCTS_KEY, []) before making HTTP call. correctly sets data on server and retrieves on client before HTTP call, optimizing performance.