0

How to combine posts and users in AngularJS, for example in a database like this. There are 2 data that are the same, namely user_id, then I want to display the username data?

[post: {post_id: 1, user_id: 2,  date: 18-05-1997}];
[user: {user_id: 2, fullname: herman, username: herman_man}];

1 Answer 1

1

First, the data should be joined and returned from the database/api layer to the front-end. However, if that is not possible, there are many ways to do this. One simple way is to do a map and return a new ViewModel. Something like this:

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.

I haven't executed the code above, it's meant to be a guide on how to do this. I've done something similar in my code.

UPDATE

Here is another SO article with other advanced options to try.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.