Population

Comments of a post of a user

Use the populate()operator to apply population to your resource.

Imagine the following scenario:

interface Post {
    id: number;
    userId: number;
    title: string;
    body: string;
}

interface Comment {
    id: number;
    postId: number;
    userId: number;
    body: number;
}

interface User {
    id: number;
    name: string;
}

Now if you want to display the user's name for every post in your list, you can use the populate() operator.

You can also fetch all comments for a post and then every user for every comment.

The populate() route instruction

Getting every post's user

import { populate, reset } from '@ng-frrri/router-middleware/operators';

const routes: Routes = [
    {
        path: 'with-user',
        component: PostsIndexComponent,
        data: operate(
            reset(all),
            populate({
                from: posts,
                to: users,
                idPath: 'userId',
                idSource: posts,
                operations: [OperationContext.Many],
            }),
        ),
    }
]

When opening /with-user, it will load all posts and then all users of the loaded posts. If you are using PaginatedHttpCollection, it will do so for every page you load.

Getting one post's comments

const routes: Routes = [
    {
    
        path: ':id',
            component: PostsShowComponent,
            data: operate(
                reset(comments),
                populate({
                    from: posts,
                    to: comments,
                    idPath: 'postId',
                    idSource: comments,
                    operations: [OperationContext.One],
                }),
                getActive(posts),
            ),
    },
];

The same configuration would also work if you would change getActive() to getMany(). This would, however, populate all comments of every post loaded by getMany().

Last updated