Skip to main content

Usage with createSelector

Imagine, there are two selectors in our Angular with NGRX app:

  • a selector that returns the id of a current user

    export const selectCurrentUserId = createSelector(  selectUserState,  feature => feature.currentUserId,);
  • a root selector for users with relationships

    export const selectUserWithCompany = rootEntity(  selectUserState,  relatedEntity(    selectCompanyFeature,    'companyId',    'company',  ),);

Then we have 3 options:

  • usage of switchMap, but it is ugly

    // selecting the id of a current userstore  .select(selectCurrentUserId)  .pipe(    // selecting the user with desired relationships    switchMap(id => store.select(selectUserWithCompany, id)),  )  .subscribe(user => {    // profit  });
  • combine the selectors together via createSelector function, but it is a bit uncomfortable

    export const selectCurrentUser = createSelector(  // selecting the whole store  s => s,  // selecting the id of a current user  selectCurrentUserId,  // selecting the user with desired relationships  selectUserWithCompany,);
    store.select(selectCurrentUser).subscribe(user => {  // profit});
  • pass an id selector as a parameter, what is the best choice and quite short

    // selecting the user with desired relationshipsstore  .select(selectUserWithCompany, selectCurrentUserId)  .subscribe(user => {    // profit  });