使用 @ngrx/effects
的值要如何操作,
我現在要新增一個 RxJS 的條件式 filter
,
對值進行過濾的動作
什麼意思? 更完整的描述會更有幫助
import { Injectable } from '@angular/core';
import { Store } from '@ngrx/store';
import { Actions, Effect } from '@ngrx/effects';
import 'rxjs/add/operator/filter';
import 'rxjs/add/operator/map';
@Injectable()
export class CounterEffects {
@Effect() incrementIfOdd$ = this.actions$
.ofType(INCREMENT_IF_ODD)
.filter(([action, state]) => state % 2 === 1)
.map(res => ({ type: INCREMENT, payload: res }));
constructor(private actions$: Actions, private state$: Store<CounterState>) { }
}
我要新增一個如果奇數時,才可以執行增加的動作
如果我用 redux-observable
,有 store
的參數,但是我看 @ngrx/effects
的文件,有點看不懂
import { filter } from 'rxjs/operator/filter';
import { map } from 'rxjs/operator/map';
const incrementIfOddEpic = (action$, store) =>
action$.ofType(INCREMENT_IF_ODD)
::filter(() => store.getState().counterReducer.get('counter') % 2 === 1)
::map(() => ({ type: INCREMENT }));
你的 INCREMENT_IF_ODD 是什麼時候被 dispatch的?
文件的 store 就跟你在 component 地方所 Inject 的 store 是同一個
有更改了,但是 … 還是不知道怎麼使用
private state$: Store<CounterState>
你確定你是用ngrx/effect嗎?
你effect那段改完的code長什麼樣子?
@Effect() incrementIfOdd$ = this.actions$
.ofType(INCREMENT_IF_ODD)
.filter(([action, state]) => state % 2 === 1)
.map(res => ({ type: INCREMENT, payload: res }));
請改為
constructor(private actions$: Actions,private state$: Store<CounterState>){}
...
@Effect() incrementIfOdd$ = this.actions$
.ofType(INCREMENT_IF_ODD)
.withLatestFrom(this.state$) <= 你漏了這行
.filter(([action, state]) => state % 2 === 1)
.map(res => ({ type: INCREMENT, payload: res }));
import { Injectable } from '@angular/core';
import { Store } from '@ngrx/store';
import { Actions, Effect } from '@ngrx/effects';
import 'rxjs/add/operator/withLatestFrom';
import 'rxjs/add/operator/filter';
import 'rxjs/add/operator/map';
@Injectable()
export class CounterEffects {
@Effect() incrementIfOdd$ = this.actions$
.ofType(INCREMENT_IF_ODD)
.withLatestFrom(this.state$)
.filter(([action, state]) => state.counter % 2 === 1)
.map(() => ({ type: INCREMENT }));
@Effect() decrementIfEven$ = this.actions$
.ofType(DECREMENT_IF_EVEN)
.withLatestFrom(this.state$)
.filter(([action, state]) => state.counter % 2 === 0)
.map(() => ({ type: DECREMENT }));
constructor(private actions$: Actions, private state$: Store<CounterState>) { }
}
解決了! 感恩!
我把 payload 拿掉了,因為還不知道 @ngrx/effects
怎麼與 payload 一起工作