在angular项目中集成ngxs,利用ngxs-storage能够实现基于localstorage的state持久化。
但是通过测试发现,不同页面间,通过action修改state,除了当前页面,其他页面通过绑定select接收不到state变化。
最终找到解决方法,利用window.onstorage实现state同步。
修改代码如下:
1)创建用于刷新状态的 refresh-actions
export interface RefreshData {
name: string;
state: any;
}
export class RefreshState {
static readonly type = '[RefreshData] RefreshState';
constructor(public data: RefreshData) { }
}
2)在AppModule中的构造函数监听window.onstorage,并发布RefreshState
export class AppModule {
constructor(private store: Store) {
window.onstorage = (ev) => {
if (ev.key !== '@@STATE') {
return;
}
const oldValue = JSON.parse(ev.oldValue);
const newValue = JSON.parse(ev.newValue);
for (const prop in newValue) {
if (JSON.stringify(newValue[prop]) === JSON.stringify(oldValue[prop])) {
continue;
}
console.log(ev);
store.dispatch(new RefreshState({
name: prop,
state: newValue[prop]
}));
}
};
}
}
3)改造需要实现跨网页同步的action,使之响应RefreshState。以下以自定义的AuthState为例,
const AUTHENTICATION_TOKEN = new StateToken<any>('authentication');
@State({
name: AUTHENTICATION_TOKEN,
defaults: null
})
@Injectable()
export class AuthState {
@Action(RefreshState)
refresh(ctx: StateContext<any>, action: RefreshState) {
if (action.data.name === AUTHENTICATION_TOKEN.getName()) {
ctx.setState(action.data.state);
}
}
}
通过以上三步,即可实现跨页面state同步。
抛砖引玉,希望能帮助到有类似需求的童靴们。