如何在NGXS的Action中设置布尔类型属性的值
解决方案
你只需要在将接口返回的证书数据写入状态前的遍历环节,直接计算aboutToExpire字段的值即可,修改getAllCertificates方法中patchState对应的数组映射逻辑即可。
核心修改点
把原来的证书数组映射逻辑,增加aboutToExpire的赋值规则:
// 原逻辑 certificates: certsResponse.certificates.map(cert => ({ ...cert, })), // 修改后逻辑 certificates: certsResponse.certificates.map(cert => ({ ...cert, aboutToExpire: cert.daysToExpire < 61 })),
filteredCertificates字段对应的映射逻辑也做完全相同的修改即可。
如果要兼容daysToExpire可能为空的异常场景,可以加兜底逻辑:
aboutToExpire: (cert.daysToExpire ?? Infinity) < 61
完整修改后的Action代码
@Action(CertificateAction.GetAllCertificates) getAllCertificates( ctx: StateContext<CertificateStateModel>, action: CertificateAction.GetAllCertificates ) { ctx.dispatch(new Busy(true)); return this.svc.getIACertificates().pipe( tap((certsResponse) => { ctx.patchState({ certificates: certsResponse.certificates.map(cert => ({ ...cert, aboutToExpire: cert.daysToExpire < 61 })), filteredCertificates: certsResponse.certificates.map(cert => ({ ...cert, aboutToExpire: cert.daysToExpire < 61 })), }); ctx.dispatch(new Busy(false)); }, (error: any) => { ctx.dispatch([ new DisplayMessage({type: "error", list: [ "Get All Certificates Error", error.error ]}), new Busy(false) ]); }) ); }
内容的提问来源于stack exchange,提问作者Jonald Monday
相关产品推荐
相关产品推荐

