My service class, before calling a web service, needs to get a property called dataForUpdate from my state. Currently, I\'m doing it like this:
I've created a minimalistic application that has a state with 2 counters which are properties of the AppState, and 2 reducers. Each reducer is bound to a particular counter, and I've subscribed an observable for each counter that will console.log its value. The reducers themselves also write to the console when called.
There is a button which calls both reducers by dispatching an event. Also, the 2 counters are bound to 2 labels, so changes in them show - Counter: {{counter1 | async}}.
Mapping each counter to a reducer is done with StoreModule.forRoot({ counter1: Reducer1, counter2 : Reducer2 })
import { Component, NgModule } from '@angular/core';
import { Store, Action, StoreModule } from '@ngrx/store';
import { Observable } from 'rxjs/Observable';
import { BrowserModule } from '@angular/platform-browser';
interface AppState {
counter1 : number;
counter2 : number;
}
export function Reducer1(counter : number = 0, action : Action) {
console.log(`Called Reducer1: counter=${counter}`);
return counter + 1;
}
export function Reducer2(counter : number = 0, action : Action) {
console.log(`Called Reducer2: counter=${counter}`);
return counter + 2;
}
@Component({
selector: 'app-root',
template: `Counter: {{counter1 | async}}
Counter: {{counter2 | async}}
`
})
export class AppComponent {
title = 'app';
counter1 : Observable;
counter2 : Observable;
constructor(private store : Store) {
this.counter1 = this.store.select('counter1');
this.counter2 = this.store.select('counter2');
this.counter1.subscribe(x => console.log(`Subscribe event for counter1 fired: counter=${x}`));
this.counter2.subscribe(x => console.log(`Subscribe event for counter2 fired: counter=${x}`));
}
increment() {
this.store.dispatch({type:'foo'});
}
}
@NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule,
StoreModule.forRoot({ counter1: Reducer1, counter2 : Reducer2 })
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }