почему значение счетчика увеличивается и уменьшается только в первый раз?

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

не могли бы вы сказать мне, почему мое значение счетчика увеличивается и уменьшается только в первый раз. У меня есть две кнопки increment и decrement значение счетчика изменяется при нажатии кнопки. но мое значение изменяется только в первый раз. он показывает 0 начальное значение, которое является правильным, но после этого не работает почему?


person user944513    schedule 25.06.2018    source источник
comment
Не могли бы вы поделиться кодом магазина?   -  person Abel Valdez    schedule 25.06.2018
comment
Я думаю, что вы делаете глупую ошибку в counter.reducer.ts .. проверьте мой ответ с помощью @Swoox   -  person MukulSharma    schedule 25.06.2018
comment
хорошо, я проверю и обновлю тебя   -  person user944513    schedule 25.06.2018


Ответы (3)


Это очень просто каждый раз, когда вы вызываете функцию: incrementCounter вы создаете новый класс new IncrementCounter(). Поэтому каждый раз, когда вы вызываете эту функцию, она будет вызывать одно и то же.

Что вам нужно сделать, так это сделать этот новый класс в области видимости компонента:

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);
  }
person Swoox    schedule 25.06.2018
comment
можешь ли ты поделиться своей ссылкой? - person user944513; 25.06.2018
comment
он работает без вашего кода, почему? stackblitz.com/edit/ - person user944513; 25.06.2018
comment
пожалуйста, удали свой ансер - person user944513; 25.06.2018

измените свою "функцию counterReducer"

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;
  }
}
person Eliseo    schedule 25.06.2018

person    schedule
comment
посмотреть, как это работает stackblitz.com/edit/ - person user944513; 25.06.2018
comment
без @swooz anser - person user944513; 25.06.2018