简体   繁体   中英

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 ?

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!)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM