如何将响应嵌套对象内的answerId作为参数传入待分发的action
解决方案
你只需要按照响应的嵌套结构逐层取出answerId,再传入action的入参即可,修改后的代码如下:
private listenToAnswerDeleted() { this.uiService.onGlobalEvent('ANSWER_DELETED').subscribe((response) => { // 从嵌套对象中提取answerId const answerId = response.extras.answerId; this.store.dispatch(deleteAnswerAction({ answerId })); }); }
如果存在类型校验、属性可能为空的场景,可以做兼容处理:
- 可选链+空值兜底,避免属性不存在时报运行时错误:
const answerId = response?.extras?.answerId ?? '';
- 未定义response类型时,可以用类型断言跳过TS校验:
// 定义明确的类型结构 const answerId = (response as {extras: {answerId: string}}).extras.answerId; // 临时兼容也可以直接使用any类型 const answerId = (response as any).extras.answerId;
内容的提问来源于stack exchange,提问作者Zahid M Shaikh
相关产品推荐
相关产品推荐

