Angular使用in-memory-web-api时createUser参数类型不匹配报错如何解决
错误原因
Argument of type '{ name: string; id: null; }' is not assignable to parameter of type 'User'. Types of property 'id' are incompatible. Type 'null' is not assignable to type 'number'.ts(2345)
这个报错是TypeScript类型校验不通过导致的,具体原因有三个:
- 你的
User数据模型中,id字段被定义为number类型,不允许为null - 你在组件中声明的临时
user对象,id初始值设为null,调用createUser方法时传入的参数包含id: null,和User类型要求不匹配 - 你
user.service.ts中createUser方法里的user.id === null;是比较操作,没有赋值效果,属于书写错误
解决步骤
- 第一步:修改
User模型的id字段属性
新增用户时id由in-memory-web-api自动生成,前端不需要传值,所以把id设置为可选或者允许null即可,打开users.model.ts修改:
export interface User { id?: number; // 设为可选属性,也可以写 id: number | null name: string; // 其余原有字段保持不变 }
- 第二步:修正服务层的错误代码
打开user.service.ts修改createUser方法,删掉无效的比较语句:
createUser(user: User): Observable<User> { // 删掉原有的 user.id === null; 这行是比较操作,没有赋值作用 return this.http.post<User>(this.usersUrl, user).pipe( catchError((error: HttpErrorResponse) => { console.error(error); return throwError(error); }) ) }
- 第三步(可选):优化组件代码
如果你不想修改User模型,可以直接在调用接口的时候不传id字段,同时做类型断言:
打开user-list.components.ts修改addUser方法:
addUser(){ const data = { name: this.user.name }; this.userService.createUser(data as User).subscribe(response => { console.log(response) this.getUsers(); }) } // 也可以直接把组件里的临时user对象加类型,避免手动写id: null user: Partial<User> = { name: '' }
内容的提问来源于stack exchange,提问作者Ousi Boi
相关产品推荐
相关产品推荐

