【发布时间】:2021-11-16 17:54:57
【问题描述】:
在使用 NodeJS 服务器的本地 MEAN 堆栈应用程序上,我的端点响应返回数组 os Post:
{
"message": "Posts fetched successfully!",
"posts": [
{
"_id": "618b22ff9e50776ed377c4eb",
"title": "aaaaaaaaaaaaaa",
"body": "xxxxxxxxxxxxx",
"__v": 0
},
]
}
带有响应模型的 Angular 服务:
export interface PostResponse {
message: string;
posts: Post;
}
getPosts(): Observable<PostResponse> {
return this.http.get<PostResponse>(this.postsUrl + '/api/posts');
}
PostComponent 注入上面的 Postservice:
export interface Post {
id: number;
title: string;
body: string;
}
export class PostsComponent implements OnInit {
posts: Post[] = [];
constructor(private postService: PostService) {}
ngOnInit() {
this.postService
.getPosts()
.pipe(
map((data) => {
console.log('data : ', data.posts._id); // vide #1
return {
id: data.posts.id, // _id error <HERE>
title: data.posts.title,
content: data.posts.body,
};
})
).subscribe((response) => {
this.posts = response; // error <HERE>
console.log('posts updated : ', this.posts);
});
}
问题。
Q-1:在我的组件上,当我映射响应数据时,所需的道具是 data.posts.id,而不是 data.posts._id,但流数据是: #1 { "_id": "618b22ff9e50776ed377c4eb", “标题”:“啊啊啊啊啊啊”, “正文”:“xxxxxxxxxxxxx”, “__v”:0 },
如果我使用 _id,我会收到错误“帖子”类型上不存在属性“_id”
这是因为我的 PostResponse 接口吗?
_id 来自我的 mongo 数据库,我假设我必须强制转换响应数据以匹配我不使用 _ID 而是使用 ID 的前端结构。
Q-2:在订阅时,在 this.posts = response 我收到错误:
输入 '{ id: number;标题:字符串;内容:字符串; }' 缺少类型 'Post[]' 的以下属性:length、pop、push、concat 和 26 more.ts(2740)
【问题讨论】:
标签: angular typescript