解决angular集成ngxs无法跨页面监听state变化

在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同步。

抛砖引玉,希望能帮助到有类似需求的童靴们。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值