如何在 AngularJS 中组合帖子和用户,例如在这样的数据库中。有2个数据相同,即user_id,那我想显示用户名数据?
[post: {post_id: 1, user_id: 2, date: 18-05-1997}];
[user: {user_id: 2, fullname: herman, username: herman_man}];
首先要将数据从数据库/api层进行Join并返回到前端。 但是,如果这是不可能的,有很多方法可以做到这一点。一种简单的方法是执行
map
并返回一个新的 ViewModel。像这样的东西:
export class PostViewModel {
post_id: number;
user_name?: string;
date: Date;
user_id: number;
}
//then in the method where you retrieve the data, after retrieving it:
// let's say you have the collections named: users and posts
let postsVm = posts.map(x=> <PostViewModel>{
post_id: x.post_id,
user_name: users.find(y=>y.user_id === x.user_id)?.username,
date: x.date,
user_id: x.user_id
});
// this should return an array of PostViewModels you can then use in the UI to display.
我还没有执行上面的代码,它只是作为如何执行此操作的指南。我在我的代码中做了类似的事情。