Angular Universal-为客户端缓存的服务器端请求 [英] Angular universal - Server side requests cached for client

查看:54
本文介绍了Angular Universal-为客户端缓存的服务器端请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经看过很多有关在有角度的通用应用程序中为客户端缓存数据的文章,因此它不会在已经在服务器上解决的客户端请求上重复.

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.

我只是不知道如何将数据从服务器传输到客户端.我应该将JSON注入预渲染的HTML还是缺少其他内容?

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 ?

推荐答案

从Angle 5开始,Angular内核中有一个名为 TransferStateModule 的模块可以为您完成此任务. https://angular.io/api/platform-b​​rowser/TransferState

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

您只需将您的API响应与StateKey(基本上就像一个字符串)一起添加到服务器端的缓存中,在将index.html文件发送到客户端之前,它会以Json的形式写入到DOM中,在那里您需要StateKey并从Json获取结果.

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.

在官方的通用入门工具包中,您可以查看注册的位置和内容: https://github.com.com/angular/universal-starter

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

更新Angular 6

Update Angular 6

您不需要自己设置状态键.新的TransferStateModule具有HttpClient拦截器,可自动设置密钥!如果您想拥有更多控制权,仍然可以自己进行操作,但是现在,添加模块变得一样简单(默认情况下,最新的通用入门工具包已将其导入!)

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

这篇关于Angular Universal-为客户端缓存的服务器端请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆