Skip to content
Angular Essentials
GitHub

Task - Add new state

  • Create a root level state name isLoggedIn which is simply a boolean. Initially isLoggedIn should be false.
  • Create required login / logout action and reducer to update state value on respective action.
  • Also, a selector which gets you the isLoggedIn state and subscribe/listen to it.
  • Add two button on header namely Login and Logout.
  • Login should only be visible when isLoggedIn is false.
  • Update isLoggedIn state to true when Login button is clicked.
  • Likewise, Logout should only be visible when isLoggedIn is true.
  • Update isLoggedIn state to false when Logout button is clicked.
  • Use guard (hint: canActivate) to allow user to access Todo Component only when they are logged in (isLoggedIn is true).

Hint: For adding root level state

// user-preferences.reducer.ts
export interface UserPreferences {
  isDarkTheme: boolean;
  defaultPage: string;
}

export const userPreferencesInitialState: UserPreferences = {
  isDarkTheme: true,
  defaultPage: 'todo_page_id'
}

export const userPreferencesReducer = createReducer(userPreferencesInitialState);
// app.reducer.ts
export interface AppState {
  userPreferences: UserPreferences;
}

export const reducers: ActionReducerMap<AppState> = {
  userPreferences: userPreferencesReducer
}
// app.module.ts
@NgModule({
  declarations: [AppComponent, VoidComponent],
  imports: [
    BrowserModule,
    AppRoutingModule,
    BrowserAnimationsModule,
    StoreModule.forRoot(reducers), // registering root level reducers here, meaning these are eagerly fetched at start of application
    EffectsModule.forRoot(),
    StoreDevtoolsModule.instrument({maxAge: 25, logOnly: environment.production}),
    HeaderModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule {
}

Just like above reducer you need to create reducer for user login / logout. Also, you need to create action as mentioned in point number two. This is just to show you how to set up initially for root level state.