Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular universal - Server side requests cached for client

I've seen many articles about caching data for client in angular universal apps, so it doesn't duplicate the requests on client that has been already resolved on server.

I just don't get how the data is transferred from server to the client. Do I inject the JSON to pre-rendered HTML or am I missing something else ?

like image 679
Stevik Avatar asked May 30 '17 12:05

Stevik


People also ask

Is angular client-side rendering or server-side rendering?

Angular applications are client-side applications that execute on the browser - which means they are rendered on the client, not on the server. You can add server-side rendering to your app using Angular Universal.

How does server-side caching work?

Server side web caching typically involves utilizing a web proxy which retains web responses from the web servers it sits in front of, effectively reducing their load and latency. Client side web caching can include browser based caching which retains a cached version of the previously visited web content.

How does angular use cached data?

GET requests can be cached. They just get data from the server without changing them. If no POST , PUT , or DELETE request occurs before the next GET request, the data from the last GET request does not change. We simply return the previous data or response without hitting the server.

What is one benefit of server-side caching in Apis?

Server caching helps limit the cost incurred by the server and its underlying systems. Many requests made by clients can either be responded to using the same data, or responded to using parts of the same requests made by others.


1 Answers

As of angular 5, there is a module inside angular core called TransferStateModule that does this for you. https://angular.io/api/platform-browser/TransferState

You simply add your API response to the cache on serverside together with an StateKey (basically just like a string), it get's written to the DOM as Json before the index.html file is send to the client, there you ask for the StateKey and get the result from the Json.

In the official Universal Starter Kit you can see where and what to register: https://github.com/angular/universal-starter


Update Angular 6

You don’t need to set the State key yourself. The new TransferStateModule has an HttpClient Interceptor that sets the keys automatically! You can still do it yourself if you want to have more control but now it’s as easy as adding the module (the newest universal starter kit has it imported by default!)

like image 87
Denis Avatar answered Oct 17 '22 20:10

Denis