NGXS派发GetUser Action时提示string无法赋值给{email:string}参数如何解决
问题根因
你定义的GetUser Action构造函数要求入参是包含email字段的对象类型{email: string},但你在调用时直接传入了字符串类型的userEmail,导致类型不匹配触发报错。除此之外你的状态处理逻辑还存在死循环隐患。
修复步骤
1. 修正组件中Action调用的传参格式
将组件getUser方法中dispatch的代码修改为传入符合类型要求的对象:
getUser() { let userEmail = localStorage.getItem('email') || ''; // 原错误写法为 new GetUser(userEmail),修改为包裹成要求的对象结构 this.store.dispatch(new GetUser({ email: userEmail })).subscribe((data) => { this.router.navigate(['/profile']); }); this.userService.getUser(userEmail).subscribe((response) => ( console.log(response) )); }
2. 移除ProfileState中的死循环代码
你在GetUser的Action处理逻辑中,拿到接口返回结果后又调用了ctx.dispatch(new GetUser(this.profile)),会导致无限重复触发拉取用户接口,直接删除该行即可,同时可删除未使用的profile实例属性:
@Action(GetUser) getUser(ctx: StateContext<ProfileStateModel>, action: GetUser ){ const state = ctx.getState(); return this.userService.getUser(action.payload.email).pipe( tap((profile) => { ctx.setState({ ...state, userProfile:profile }); // 删除下方这行死循环代码即可 // ctx.dispatch(new GetUser(this.profile)); }) ); }
历史同类问题说明
之前你用userId传参时遇到的报错也是相同原因:Action构造函数要求传入{userId: number}类型的对象,你直接传了number类型的userId值,改为包裹成对象传入即可解决。
内容的提问来源于stack exchange,提问作者Kevin
相关产品推荐
相关产品推荐

