我试图在页面刷新之间保留状态,但是似乎丢失了状态信息。我试图保存两个布尔值并检索它。我已经为chrome安装了NGXS Dev工具来检查状态。我可以看到该动作正确地调度了状态信息,但是当我按F5键时,该信息就会丢失。我想念什么?
动作
import { AgreementsStateModel } from '../models/agreements-state.model';
export class SetAgreementStatus {
static readonly type = '[AGREEMENT] SetAgreementStatus';
constructor(public payload: AgreementsStateModel) {}
}
状态
import { Action, Selector, State, StateContext } from '@ngxs/store';
import { AgreementsStateModel } from '../models/agreements-state.model';
import { SetAgreementStatus } from './agreement.actions';
@State<AgreementsStateModel>({
name: 'agreementModalState',
defaults: {
isDeferred: false,
isInteracted: false
}
})
export class AgreementState {
constructor() { }
@Selector()
static agreement(state: AgreementsStateModel) {
return state;
}
@Action(SetAgreementStatus)
setAgreementStatus({ patchState }: StateContext<AgreementsStateModel>, { payload }: SetAgreementStatus) {
patchState(payload);
}
}
AppModule导入
NgxsStoragePluginModule.forRoot()
调度状态
this.store.dispatch(new SetAgreementStatus({isInteracted: true, isDeferred: true}));
读取状态信息
@Select(AgreementState.agreement) agreementModalState$: Observable<AgreementsStateModel>;
this.agreementModalState$.subscribe(agreementModalStatus => {
this.agreementModalStatus = agreementModalStatus;
});
答案 0 :(得分:1)
因此,NGRX存储不会在刷新期间保留信息。您将必须使用用户localStorage
或其他本地存储设备来存储此信息。
一种方法是在减速器中,也可以将您在商店中设置的相同信息存储在用户localStorage
中,然后在刷新时,可以获取已存储的任何信息并填充您的商店。
有许多尝试简化此过程的库,例如ngrx-store-localstorage,它们可以同步商店和用户localStorage
,这样您就不会在刷新之间丢失状态
但是默认情况下,ngrx存储不会在页面刷新之间保存信息