Blog>
Snippets

Angular Universal TransferState API

Demonstrate the use of TransferState API to pass data from server to client seamlessly in an Angular Universal app.
import { TransferState, makeStateKey } from '@angular/platform-browser';

// Create a key for the data to be transferred
const MY_DATA_KEY = makeStateKey('myDataKey');
Import TransferState and makeStateKey from the Angular platform-browser package, and create a state key for the data.
@Injectable()
class MyService {
  constructor(private http: HttpClient, private transferState: TransferState) {}

  getData(): Observable<MyDataType> {
    // First, check if data is already in TransferState
    if (this.transferState.hasKey(MY_DATA_KEY)) {
      // Use the data from TransferState
      const data = this.transferState.get<MyDataType>(MY_DATA_KEY, null);
      this.transferState.remove(MY_DATA_KEY); // Optionally remove the data
      return of(data);
    } else {
      // Otherwise, fetch the data from the server
      return this.http.get<MyDataType>('https://my.api/data').pipe(
        tap(data => {
          // Save the data to TransferState
          this.transferState.set(MY_DATA_KEY, data);
        })
      );
    }
  }
}
In an Injectable service, implement the data retrieval method, using TransferState to either return cached data or fetch from the server and store it.
@Component({
  // Component metadata
})
class MyComponent {
  data: MyDataType;

  constructor(private myService: MyService) {}

  ngOnInit() {
    // Call the service to get data on initialization
    this.myService.getData().subscribe(data => {
      this.data = data;
    });
  }
}
Inside an Angular component, inject the custom service and call the getData method on ngOnInit to retrieve data from TransferState or the server.
import { BrowserModule, BrowserTransferStateModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';

// Other imports...

@NgModule({
  // ... Module setup
  imports: [
    BrowserModule.withServerTransition({appId: 'my-app'}),
    BrowserTransferStateModule // <-- include the module to enable TransferState
    // ... Other imports
  ]
  // ...
})
class MyAppModule {}
Include BrowserTransferStateModule in the module imports to enable TransferState in the client app module.
import { NgModule } from '@angular/core';
import { ServerModule, ServerTransferStateModule } from '@angular/platform-server';

// Other imports...

@NgModule({
  // ... Module setup
  imports: [
    ServerModule,
    ServerTransferStateModule, // <-- include the module for server-side TransferState
    // ... Other imports
  ]
  // ...
})
class AppServerModule {}
Include ServerTransferStateModule in the server app module imports to enable TransferState on the server side.