transfer-state-utils
TypeScript icon, indicating that this package has built-in type declarations

0.0.1 • Public • Published

TransferState Utils

A small utility to set (on server) and get (on browser) TransferState values.

Getting started

Install the package with:

npm install transfer-state-utils

Usage

getOrSet()

getOrSet<T>(key: string, value: T): T | null

Parameters

  • key - Name of the key
  • value - The server side value to store

Example

Let's say you have the following Express route to server-side render your app. It injects a token containing a value passed from Express server:

// SSR using an Express server from Angular Universal
server.get('*', async (req, res) => {
  res.render(indexHtml, {
    req, providers: [
      { provide: APP_BASE_HREF, useValue: req.baseUrl },
      // Inject a value from the server
      // Here we are passing a string, but this could be data from your database or other sources
      { provide: 'message', useValue: 'Test message from server' }
    ]
  });
});

You can use the getOrSet function in your component to set the value in TransferState when run on the server, and get the value when run on the browser:

@Component({
  selector: 'app-root',
  template: `{{ message }}`,
})
export class AppComponent {
  message: string;

  constructor(
    // Injection token from Express server
    @Optional() @Inject('message') private messageFromServer: string
  ) {
    // When rendered on the server, set the value in TransferState
    // When rendered on the client, get the value from TransferState
    this.message = getOrSet('message', messageFromServer);
  }
}

Readme

Keywords

none

Package Sidebar

Install

npm i transfer-state-utils

Weekly Downloads

1

Version

0.0.1

License

none

Unpacked Size

9.28 kB

Total Files

10

Last publish

Collaborators

  • kgajera