Implementing Components

To demonstrate how to use the CounterService in your components, let's start by building out a small CounterComponent. The component will beresponsible for incrementing and decrementing the counter by one, as well asallowing the user to reset the counter to zero.

app/components/counter.component.ts

  1. import {Component, Input} from '@angular/core';
  2. import {Observable} from 'rxjs/Observable';
  3. import {CounterService} from '../services';
  4. import {CounterActions} from '../store/counter/counter.actions';
  5. @Component({
  6. selector: 'counter',
  7. templateUrl: './counter.component.html'
  8. })
  9. export class CounterComponent {
  10. private currentValue$: Observable<number>;
  11. constructor(
  12. counterService: CounterService,
  13. public actions: CounterActions
  14. ) {
  15. this.currentValue$ = counterService.getCurrentValue();
  16. }
  17. }

app/components/counter.component.html

  1. <p>
  2. Clicked: {{currentValue$ | async}} times
  3. <button (click)="actions.increment()">+</button>
  4. <button (click)="actions.decrement()">-</button>
  5. <button (click)="actions.reset()">Reset</button>
  6. </p>

The template syntax should be familiar by now, displaying an Observable counter value with the async pipe. Any time appState.counter.currentValue isupdated by a reducer, currentValue$ will receive the new value and | async will update it in the template.

The component also handles some click events. Each click event is bound to expressions that call our action creators from the CounterActions ActionCreatorService.

原文: https://angular-2-training-book.rangle.io/handout/state-management/ngrx/implementing_components.html