Angular universal - Server side requests cached for client

不想你离开。 提交于 2021-01-27 05:53:55

问题


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 ?


回答1:


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



来源:https://stackoverflow.com/questions/44261914/angular-universal-server-side-requests-cached-for-client

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!