Creating Selectors page

Learn how to create NgRx Selectors to obtain data from States.

Quick Start: You can checkout this branch to get your codebase ready to work on this section.

Overview

  1. Create Selector for userId.

  2. Create Selector for username.

  3. Create Selector for token.

Problem 1: Creating a Feature Selector For userId

There should be a Selector that obtains the userId from the Login State.

P1: What you need to know

NgRx Selectors are pure functions used for obtaining slices of state.

NgRx provide 2 helper functions when creating Selectors:

  1. createFeatureSelector - Used to obtain the entire Feature State from the Global State by looking up the Login Feature key.

  2. createSelector - Uses other Selectors to obtain slices of state. The first arguments are any other Selectors used for this new Selector. The last argument of this function is a pure function commonly referred to as a projector.

The NgRx schematics take care of creating our Login Selector, and it’s up to us to create additional Selectors using that generated Feature Selector to obtain slices of that state:

import { createFeatureSelector, createSelector } from '@ngrx/store';
import * as fromContact from './contact.reducer';

// Generated Feature Selector
export const selectContactState = createFeatureSelector<fromContact.State>(
  fromContact.contactFeatureKey
);

// Selector that obtains email address from Feature State
export const selectContactEmailAddress = createSelector(
  selectContactState,
  state => state.emailAddress
);

P1: Solution

src/app/store/login/login.selectors.ts

// src/app/store/login/login.selectors.ts

import { createFeatureSelector, createSelector } from '@ngrx/store';
import * as fromLogin from './login.reducer';

export const selectLoginState = createFeatureSelector<fromLogin.State>(
  fromLogin.loginFeatureKey
);

export const selectUserId = createSelector(
  selectLoginState,
  state => state.userId
);

Problem 2: Creating a Feature Selector For username and token

There should be a Selector that obtains the username and another Selector for token. Both should obtain values from the Login State.

P2: Solution

src/app/store/login/login.selectors.ts

// src/app/store/login/login.selectors.ts

import { createFeatureSelector, createSelector } from '@ngrx/store';
import * as fromLogin from './login.reducer';

export const selectLoginState = createFeatureSelector<fromLogin.State>(
  fromLogin.loginFeatureKey
);

export const selectUserId = createSelector(
  selectLoginState,
  state => state.userId
);

export const selectUsername = createSelector(
  selectLoginState,
  state => state.username
);

export const selectToken = createSelector(
  selectLoginState,
  state => state.token
);

Wrap-up: By the end of this section, your code should match this branch. You can also compare the code changes for our solution to this section on GitHub or you can use the following command in your terminal:

git diff origin/create-selectors