Angular 2 micro application with NgRx store
- app.module.ts
import { Component, NgModule } from '@angular/core'
import { Store, Action, StoreModule } from '@ngrx/store'
import { Observable } from 'rxjs'
import { BrowserModule } from '@angular/platform-browser'
interface AppState {
counter: number
}
export function reducer(counter: number = 0, action: Action) {
console.log('#called reducer with action.type=' + action.type)
return counter + 1
}
@Component({
selector: 'app-root',
template: `
<p>CounterObject: {{counterObject | async}}</p>
<p>CounterValue: {{counterValue }}</p>
<button class="button" (click)='increment()'>Increment</button>
`
})
export class AppComponent {
title = 'app'
counterObject: Observable<number>
counterValue: number = 0
constructor(private store: Store<AppState> ) {
this.counterObject = this.store.select('counterReducer')
this.counterObject.subscribe((value) => {
console.log('#new value of counter=' + value)
this.counterValue = value
})
}
increment() {
this.store.dispatch({
type: 'foo'
})
}
}
@NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule,
StoreModule.forRoot({
counterReducer: reducer,
})
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule {}
Output
Angular is running in the development mode.
Call enableProdMode() to enable the production mode. vendor.js:49088:9
#called reducer with action.type=foo main.js:89:5
#new value of counter=2 main.js:100:13
#called reducer with action.type=foo main.js:89:5
#new value of counter=3 main.js:100:13
#called reducer with action.type=foo main.js:89:5
#new value of counter=4 main.js:100:13
#called reducer with action.type=foo main.js:89:5
#new value of counter=5 main.js:100:13
#called reducer with action.type=foo main.js:89:5
#new value of counter=6 main.js:100:13