SSR-angular
Angular 中的 ssr
虽然 Angular 的数据是保存在 service 中的,但是 angular 并不是像 pinia 一样默认将 service 作为整体进行 ssr。
Angular 的 ssr 是基于TransferState
和makeStateKey
实现的。
首先是makeStateKey
用于创建需要 ssr 的数据对应的 key,对应于 pinia 中的 useStore 的 id,客户端水合的时候就可以通过 id 找到服务端传递到客户端的数据。
关键在于makeStateKey
并不是给某个 service 生成一个 key,只能算是 service 的一个属性的一个临时变量。
ts
export class NewsComponent implements OnInit {
news: News[];
constructor(private http: HttpClient, private transferState: TransferState) {}
ngOnInit() {
const newsKey = makeStateKey<News[]>('news');
const newsFromState = this.transferState.get(newsKey, null);
if (newsFromState) {
this.news = newsFromState; // 从服务端状态中获取数据
} else {
this.http.get<News[]>('https://api.news.com/latest').subscribe(data => {
this.news = data;
this.transferState.set(newsKey, data); // 设置服务端的状态
});
}
}
}
html
<script id="ng-state" type="application/json">
{
"news": [
{ "id": 1, "title": "新闻标题1", "content": "内容1" },
{ "id": 2, "title": "新闻标题2", "content": "内容2" }
]
}
</script>
从这个例子中可以看出整个过程是需要手动调用transferState的get/set方法来维护数据的ssr机制。并不像pinia那样是对业务透明的。