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

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

问题描述

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

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 ?

推荐答案

从 angular 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/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 通用 - 为客户端缓存的服务器端请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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