Angular SSR 水合时 Signals 使用浏览器状态如何避免错误
明确结论:不要让 Signals 的初始值在服务端和浏览器首次渲染时不同。localStorage 只能在 hydration 完成后读取;如果某个偏好必须参与 SSR 首屏且不能闪烁,它就不能是纯浏览器状态,应改用服务端可读的 Cookie、请求头或用户配置,或者把该区块延迟到 hydration 后并接受占位。isPlatformBrowser() 只能防止服务端访问浏览器 API 报错,不能消除不一致;afterNextRender() 可以避开 NG0500,但会带来先默认值、后真实值的闪烁。
原因
Angular hydration 要求服务端 HTML 与客户端首次渲染结果一致。service 如果在构造函数里同步读 localStorage,浏览器首帧就会得到 dark/true,而服务端只能得到 light/false;如果差异影响 *ngIf/@if、列表长度或 DOM 结构,就会触发 NG0500: Hydration Node Mismatch。Signals 只是状态容器,不会自动把浏览器本地状态同步到服务端。
推荐分两类处理
- SSR 首屏需要且不能闪烁的偏好:theme、language、sidebar 初始展开状态等,用 Cookie 或请求头在服务端和浏览器都读取同一份初始值。localStorage 只作为浏览器缓存,不作为 hydration 首帧来源。
- 纯浏览器偏好:compactMode、表格列宽等,SSR 和 hydration 首次渲染都使用固定默认值;在 afterNextRender() 中一次性恢复,并用 ready 信号控制需要延迟显示的部分。
多偏好统一结构示例
把多个 signal 合并成一个 state signal,用 computed 暴露选择器,避免每个偏好各写一套读写逻辑。
import {
Injectable, signal, computed, inject, afterNextRender,
effect, isPlatformBrowser, PLATFORM_ID
} from '@angular/core';
type Theme = 'light' | 'dark';
interface Preferences {
theme: Theme;
language: string;
compactMode: boolean;
tableSettings: Record<string, unknown>;
sidebarOpen: boolean;
}
const DEFAULTS: Preferences = {
theme: 'light',
language: 'en',
compactMode: false,
tableSettings: {},
sidebarOpen: true,
};
@Injectable({ providedIn: 'root' })
export class UserPreferencesService {
private readonly storage = inject(StorageService);
private readonly platformId = inject(PLATFORM_ID);
private readonly state = signal<Preferences>(DEFAULTS);
readonly ready = signal(false);
readonly theme = computed(() => this.state().theme);
readonly language = computed(() => this.state().language);
readonly compactMode = computed(() => this.state().compactMode);
readonly sidebarOpen = computed(() => this.state().sidebarOpen);
constructor() {
afterNextRender(() => {
if (!isPlatformBrowser(this.platformId)) return;
const saved = this.storage.getJson<Partial<Preferences>>('user-preferences');
if (saved) {
this.state.update(current => ({ ...current, ...saved }));
}
this.ready.set(true);
});
effect(() => {
if (!isPlatformBrowser(this.platformId)) return;
if (!this.ready()) return;
this.storage.setJson('user-preferences', this.state());
});
}
setTheme(theme: Theme) {
this.state.update(s => ({ ...s, theme }));
}
setCompactMode(enabled: boolean) {
this.state.update(s => ({ ...s, compactMode: enabled }));
}
}
注意 effect 里必须有 ready 守卫,否则 hydration 后可能先用默认值把 localStorage 覆盖掉。
需要首屏准确时
如果 theme 或 language 必须首屏正确,就不要等到 afterNextRender。可以让服务端从 Cookie 读取同一份偏好并作为初始值;如果服务端从用户配置接口拿到状态,用 TransferState 把服务端状态传给浏览器,浏览器首次渲染用 TransferState 而不是 localStorage。这样服务端和客户端首帧一致,也没有闪烁。
对于 theme,还可以在 Angular 启动前用 index.html 里的内联脚本从 localStorage 设置 html 属性,让 CSS 先应用主题:
<script>
try {
const saved = JSON.parse(localStorage.getItem('user-preferences') || '{}');
if (saved.theme) document.documentElement.dataset.theme = saved.theme;
} catch {}
</script>
但这只是视觉兜底;如果模板结构依赖该状态,仍应使用 Cookie/TransferState 或稳定占位。
注意事项
不要在组件里直接读 localStorage;统一放到 storage 适配层。服务端版本要提供 no-op 或基于 Cookie 的实现。不要用 ngSkipHydration 作为常规方案。对纯浏览器状态,SSR 首屏拿不到真实值,零闪烁和零占位不可能同时成立,只能在 Cookie/请求头、延迟显示和占位之间取舍。
备注:内容仅供参考。
