我有一个GET请求,如果我将创建者作为api / watchlist /?creator = 5dac9d3567aca81e40bfc0之类的参数添加到帖子中,然后在Postman中对其进行测试,结果将正确返回该创建者的所有帖子以及以下代码。 / p>
app.js
app.get('/api/watchlist',(req, res, next)=>{
Watching.find({ creator: req.query.creator})
.then(documents => {
console.log("Creator value: " + req.query.creator);
res.status(200).json({
message: 'User\'s watchlist items retrieved!',
posts: documents
});
});
});
如果我尝试将GET请求拉入angular,那么它什么也不会返回。
当我打开相关网页时,前端也说前端在说ERROR TypeError: "retrievedData.posts is undefined"
getWatchListItems watch-list.service.ts:72
watch-list.service.ts
getWatchListItems(创建者:字符串){
this.http
.get<{ message: string; posts: any; maxPosts: number; watchlist: string }>(
"http://localhost:3000/api/watchlist?creator=" + creator
)
.pipe(
map(retrievedData => {
console.log(retrievedData.watchlist);
return {
posts: retrievedData.posts.map(post => {
console.log(retrievedData.watchlist);
return {
title: post.title,
cost: post.cost,
listingOwner: post.listingOwner,
id: post._id
};
}),
maxPosts: retrievedData .maxPosts
};
})
)
.subscribe(transformedPostData => {
console.log(transformedPostData);
this.posts = transformedPostData.posts;
this.postsUpdated.next({
listing: [...this.posts],
postCount: transformedPostData.maxPosts
});
});
}
watching.component.ts
ngOnInit() {
this.userId = localStorage.getItem("userId: ");
// this.userId = this.authService.getUserId();
this.watchListService.getWatchListItems(this.userId);
this.postsSub = this.watchListService
.getPostUpdateListener()
.subscribe((postData: { listing: Watching[]; postCount: number }) => {
this.totalPosts = postData.postCount;
this.posts = postData.listing;
});
}
答案 0 :(得分:1)
您将在角服务中将创建作为路径参数发送。
因此,您需要像这样修改api:
app.get('/api/watchlist/:creater', (req, res, next) => {
Watching.find({ creator: req.params.creator })
.then(documents => {
console.log("Creator value: ", req.params.creator);
res.status(200).json({
message: 'User\'s watchlist items retrieved!',
watchlist: documents
});
});
});
如果您不想更改api,则应将创建者作为查询参数发送,如下所示:
return this.http
.get<{ message: string; posts: any; maxPosts: number }>(
"http://localhost:3000/api/watchlist?creator=" + creator
)
此后,您必须按角度处理响应数据,并转换为您的需求。
您可以通过在console.log结果中包含此代码来更新问题吗? (据我所知,您不需要订阅该服务,就是在订阅您的组件)
getWatchListItems(creator: string) {
return this.http("http://localhost:3000/api/watchlist?creator=" + creator)
.pipe(
map(retrievedData => {
console.log("retrievedData: ", retrievedData);
//todo: transform retrievedData
return retrievedData;
})
)
}
别忘了您的api以这种格式返回数据,因此您应该
{
"watchlist": ...
"message": ...
}