loading...

Angular idle game tutorial: selectors and state on the page

akkonrad profile image akkonrad Updated on ・2 min read

Hi. To justify myself - all my kids are sick and I was overloaded with work and I couldn't find any time to continue this, but here I am again! Today I will quickly just show you how to display the changing state on the page. Let's start!

Selectors

What are selectors you can read in the official guide. We will use them to show the current time value from our store.

We need to create a service that will return our selectors - here it is.

// store/time.selectors.ts

import { createSelector, Store } from '@ngrx/store';
import { AppState, TimeState } from './app.state';
import { Injectable } from '@angular/core';
import { Observable } from 'rxjs';

export const selectTime = (state: AppState) => state.time;

export const selectSeconds = createSelector(
    selectTime,
    (state: TimeState) => state.seconds
);

@Injectable()
export class SelectorsService {
    constructor(private store: Store<AppState>) { }

    selectSeconds(): Observable<number> {
        return this.store.select(selectSeconds);
    }
}

Do not forget to add the service to the app.module.ts providers array.

Component

Now, to display the changing value in our app, we need to read the value from the store with service and pass it into the view. I've added OnInit method to the app.component.ts and I subscribe to the selector, so every time the state time will change, new event will be emitted to the observable. Here is the ngOnInit function:

// ...
ngOnInit(): void {
    this.subscriptions.push(this.selectors.selectSeconds().subscribe(time => this.time = time));
  }
// ...

And that's it! If you refresh the page here is what you will see below.

The view

Resources

Git repo: day 3
Preview

Posted on by:

Discussion

pic
Editor guide