Angular Universal Transfer State

Haseeb Ahmad
2 min readApr 17, 2020

--

Here is how I have managed to avoid a flicker and multiple data/api calls to backend for getting the same data when angular is getting bootstrapped in browser.

When you integrate Server Side Rendering into front end driven application made with angular or any other javascript framework e.g react, vuejs etc, you will see a common issue of transferring data from server rendered angular application to browser rendered application.

When angular application is running on server we call the api to get some data and in order to get that same on data when application runs/load on browser we don’t need to call that same api to get data on browser level as well.

Resolution:

To resolve this issue angular has introduced a module BrowserTransferStateModule in @angular/platform-browser package. Using this module we can prevent an extra that we need to make to get the same data on browser level.

How it works:

BrowserTransferStateModule helps you define data that you need send to the browser along with the rendered application from your server to browser.

What it does in angular is create a script tag

<script id="application-name-state" type="application/json"></script>

and add this tag to the rendered html sent to browser from your backend running angular universal, then when angular application is bootstrapped in browser we can get the data from BrowserTransferStateModule in our application and BrowserTransferStateModule will get the data from the above script tag. This script tag will contain the data in Key value format.

Implementation Details:

Implementation is quite simple that we need to define some state keys under which we will categories different data we need to store.

Mainly we will need TransferState, makeStateKey and StateKey.

TransferState is a storage manager like class which gives us functions to set and get the data we can store against different StateKeys, and makeStateKey is a helper function which we will use to define a StateKey.

In my implementation I have mainly used it for storing the data from Http calls made to backend server.

My first step was to create a service name DataStateService that I can use in order to store and get the data under defined StateKey.

This service is pretty simple and gives us a function named “checkAndGetData” which can be takes a StateKey under which data should be stored or checked and Observable to get data from in case data is not stored under given key.

Usage of how we can use this service is shows in the example Hero service below.

Conclusion:

Integrating angular universal for server side rendering will come with it own issues but angular has provided a solution that make things easy for the developers.

--

--

Haseeb Ahmad

I am a full stack developer and love to build software using the new technologies.