简体   繁体   中英

why counter value increment and decrement only first time?

https://stackblitz.com/edit/angular-q8nsfz?file=src%2Fapp%2Fapp.component.ts

import {Component, OnInit} from '@angular/core';
import {Store} from '@ngrx/store';
import {Observable} from 'rxjs';

import * as fromApp from './app.store';
import {DecrementCounter, IncrementCounter} from './store/counter.action';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit{
  c: Observable<object>;

  constructor(private store: Store<fromApp.AppState>) {
  }

  incrementCounter() {
     this.store.dispatch(new IncrementCounter());
  }

  decrementCounter() {
    this.store.dispatch(new DecrementCounter());
  }
  ngOnInit(){
    this.c =this.store.select('counterValue');

  }
}

Hi

can you please tell me why my counter value increment and decrement only first time .I have two button increment and decrement the counter value change on button click .but my value change only first time .it show 0 initial value which is correct but after that it don't work why ?

It's very simple every time when you call the function: incrementCounter you make a new class new IncrementCounter() . So every time when you call this function it will excute the same thing.

What you need to do is make this new class on the scope of the component:

private incrementClass = new IncrementCounter();
private decrementClass = new DecrementCounter();

  constructor(private store: Store<fromApp.AppState>) {
  }

  incrementCounter() {
     this.store.dispatch(this.incrementClass);
  }

  decrementCounter() {
    this.store.dispatch(this.decrementClass);
  }

change your "counterReducer function"

export function counterReducer(state = initialState, action: CounterActions.CounterManagment) {
  switch (action.type) {
    case CounterActions.INCREMENT:
      const counter = initialState.counter++; //see, you increment the variable initialState.counter, and then return it
      return {...state, counter};
    case CounterActions.DECREMENT:
      const currentCounter = initialState.counter--;
      return {...state, counter: currentCounter}; //idem decrement
    default :
      return state;
  }
}
Replace initialState.counter + 1 to state.counter + 1;

  switch (action.type) {
    case CounterActions.INCREMENT:
      const counter = state.counter + 1;
      return {...state, counter};
    case CounterActions.DECREMENT:
      const currentCounter = state.counter - 1;
      return {...state, counter: currentCounter};
    default :
      return state;
  }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM