skip to Main Content

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}];

2

Answers


  1. Chosen as BEST ANSWER

    I asked for angular js not angular io


  2. 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.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search