Angular MEAN栈处理Mongo Post返回数据的TypeScript类型报错问题
问题1解答
你判断的没错,该报错确实是PostResponse接口定义错误导致的,具体有两个问题:
- 后端返回的
posts字段是数组结构,但你定义的PostResponse里把posts设为了单个Post类型,结构不匹配 - 你当前定义的
Post是前端业务层使用的结构,没有包含Mongo返回的_id字段,TypeScript做静态类型校验时找不到该字段自然会抛出错误。
修复方案
单独定义后端返回的原始数据类型,和前端业务类型做拆分:
// 匹配后端返回的原始Post结构 interface RawPost { _id: string; title: string; body: string; __v: number; } // 修正PostResponse的类型定义 export interface PostResponse { message: string; posts: RawPost[]; // 这里是数组类型 }
问题2解答
该报错是因为你在map操作符中直接返回了单个对象,而this.posts声明为Post[]数组类型,单个对象不具备数组的length、push等属性和方法,所以类型不匹配。
另外注意Mongo生成的_id是字符串格式,不要把前端Post的id字段定义为number类型。
修复方案
修正map中的逻辑,遍历后端返回的posts数组,逐个转换为前端业务结构:
// 前端业务用Post结构,按需调整字段即可 export interface Post { id: string; title: string; content: string; } export class PostsComponent implements OnInit { posts: Post[] = []; constructor(private postService: PostService) {} ngOnInit() { this.postService .getPosts() .pipe( map((data) => { // 遍历数组做字段映射 return data.posts.map(rawItem => ({ id: rawItem._id, title: rawItem.title, content: rawItem.body })) }) ).subscribe((response) => { this.posts = response; console.log('posts updated : ', this.posts); }); } }
内容的提问来源于stack exchange,提问作者bernlt
相关产品推荐
相关产品推荐

