Introducing TransferState

Say Hello to TransferState, a key-value registry that is passed along with the application bundle, from the server-side angular to the browser-side part of the application. In this lesson you will learn how frontend can get to know what backend has already do (ie retrieving data from DB); thanks to that you can avoid repeating those steps and offload your application backend.

Introducing TransferState#

First, you need to provide the modules that contain the TransferState service.

Update src/app/app.module.ts by adding BrowserTransferStateModule to the @angular/platform-browser import statement:

Add it to the imports array of AppModule:

Update src/app/app.server.module.ts by adding ServerTransferStateModule to the @angular/platform-server import statement:

Add it to the imports array of AppServerModule:

Adjusting product services#

You need to prepare keys that you will use in services responsible for retrieving products. Create a new file, src/model/state-keys.ts, and add the following code:

Import TransferState and StateKeys, and then add the tap operator to the rxjs import statement in src/app/products-server.service.ts:

Inject the TransferState service, then update the getProducts() and getProduct(productId) methods to set entries to the TransferState registry when data is returned from the database. You can do it by introducing the tap operator into the observables returned by those methods:

The browser side#

Now you need to retrieve data from the TransferState registry in the browser. Adjust import statements in src/app/products.service.ts by adding the following entries:


This page is a preview of The newline Guide to Angular Universal

No discussions yet