TransferHttpCacheModule
Next step is to get know a TransferHttpCacheModule, which provides the TransferState functionality "out of the box" for the HTTP calls.
In the previous lesson, you've learned how to adjust services responsible for data retrieval to use the TransferState
registry. What if the application doesn't retrieve data from the database but performs an HTTP call instead? This may occur if your web application communicates with services that are not deployed on the same machine, such as in a microservice architecture.
Should you prepare a special server-side implementation of such a service? Fortunately, you don't need to. Instead, you can use the TransferHttpCacheModule
module that is shipped with the @nguniversal
library. This module provides HTTP_INTERCEPTOR
: a mechanism for altering HTTP calls and responses "on the fly", which uses the TransferState
registry under the hood. On the server, the interceptor feeds TransferState
with data retrieved via HTTP requests. In the browser, it looks up for these entries in the registry and does not repeat HTTP calls.
Creating a microservice#
Create a new npm project outside of your Angular Universal application, and install dependencies that are necessary to publish a basic HTTP API:
cd ..
mkdir my-service
cd my-service
git init
npx gitignore node
npm init -y
npm install express body-parser cors
touch index.js
This service will broadcast information about promotions and opening hours of the terrain shop that stands behind your online grocery. Add the following code to index.js:
const express = require('express');
const cors = require('cors');
const app = express();
const port = process.env.PORT || 8080;
app.use(
cors({
origin: true,
credentials: true,
})
);
app.get('/opening', (req, res) => {
console.log('GET opening');
res.send({ open: '8 AM', close: '10 PM' });
});
app.get('/promotions', (req, res) => {
console.log('GET promotions');
res.send(['Buy four potatoes and pay for three!']);
});
app.listen(port, () => {
console.log(
`Backend is runing on: http://localhost:${port}`
);
});
The code above introduces two API endpoints:
GET /promotions
GET /opening
Update package.json to be able to deploy this service to Heroku:
"scripts": {
"start": "node index.js",
"test": "echo \"Error: no test specified\" && exit 1"
},
Deploying to Heroku#
Create and deploy a new Heroku application:
heroku create
git add .
git commit -am "make it better"
git push heroku master
Verify the deployment with Postman or cURL:

Consuming the microservice#
Add the terrainShopBasePath
entry to src/environments/environment.ts:
export const environment = {
production: false,
apiBasePath: 'http://localhost:4200',
terrainShopBasePath: 'http://localhost:8080',
};
Add the same entry to src/environments/environment.prod.ts:
This page is a preview of The newline Guide to Angular Universal