Angular dispatch参数类型不匹配求助:string无法赋值给{id:string}类型
修复Angular NgRx Dispatch参数类型不匹配问题
问题原因
你调用store$.dispatch时传入的是字符串类型的this.id,但getCharDetailData这个action creator要求的参数是包含id字段的对象类型{ id: string },所以触发了类型不兼容错误。
修复步骤
直接将字符串参数包装成符合要求的对象结构即可:
修改组件中getCharacterDetail方法里的dispatch调用行:
// 原错误代码 this.store$.dispatch(getCharDetailData(this.id)); // 修改后代码 this.store$.dispatch(getCharDetailData({ id: this.id }));
补充说明
你的getCharDetailData action creator的定义应该类似这样(NgRx标准写法),明确要求payload是带id的对象:
import { createAction, props } from '@ngrx/store'; export const getCharDetailData = createAction( '[Character] Fetch Detail Data', props<{ id: string }>() // 这里定义了参数必须是包含id字段的对象 );
因为你在组件里已经通过if (!this.id)做了空值判断,所以此时this.id的类型已经被缩小为string,不需要额外处理空值问题。
内容的提问来源于stack exchange,提问作者Nick AL
相关产品推荐
相关产品推荐

