问题描述
我正在尝试了解ngrx/效果.我建立了一个简单的函数,每次单击将数字递增1.但是单击时它会无限循环,不确定发生了什么.我确定我犯了一些愚蠢的错误.
I'm trying to understand ngrx/effects. I have built a simple function that increments number by 1 with each click. But it's going in an infinite loop when clicked, not sure whats going on. I'm sure im making some stupid mistake.
monitor.effects.ts
monitor.effects.ts
@Injectable()
export class MonitorEffects {
@Effect()
compute$: Observable<Action> = this.actions$
.ofType(monitor.ActionTypes.INCREMENT)
.map((action: monitor.IncrementAction) => action.payload)
.switchMap(payload => {
return this.http.get('https://jsonplaceholder.typicode.com/users')
.map(data => new monitor.IncrementAction(payload+1))
.catch(err => of(new monitor.InitialAction(0)))
});
constructor(private actions$: Actions, private http:Http ) {};
}
monitor.component.ts
monitor.component.ts
ngOnInit() {
this.storeSubsciber = this
.store
.select('monitor')
.subscribe((data: IMonitor.State) => {
this.value = data.value;
this.errorMsg = data.error;
this.currentState = data.currentState;
});
}
increment(value: number) {
this.store.dispatch(new monitorActions.IncrementAction(value));
}
monitor.reducer.ts
monitor.reducer.ts
export const monitorReducer: ActionReducer<IMonitor.State> = (state = initialState, action: Actions) => {
switch (action.type) {
case ActionTypes.INCREMENT:
return Object.assign({}, { value: action.payload, currentState: ActionTypes.INCREMENT, error: null });
...
...
...
default:
return Object.assign({}, { value: 0, currentState: ActionTypes.INITIAL, error: null });
}
}
推荐答案
Effect
允许您观察给定的操作类型,并在每次分派操作时对该操作做出反应.
An Effect
allows you watch a given action type and react to that action every time it's been dispatched.
因此,如果您以某种效果观看动作X并从该效果中分派另一个动作X,您将陷入无限循环.
So if you watch actions X in some effect and dispatch from that effect another action X, you'll end up in an infinite loop.
在您的情况下:您的操作类型为.ofType(monitor.ActionTypes.INCREMENT)
,然后从效果中分派一个操作monitor.ActionTypes.INCREMENT
(根据这一部分,我假定为:monitor.IncrementAction(payload+1)
),然后再次触发该效果,然后再次,...
In your case : Your action is of type .ofType(monitor.ActionTypes.INCREMENT)
and from your effect you then dispatch an action monitor.ActionTypes.INCREMENT
(from this part I assume : monitor.IncrementAction(payload+1)
), then the effect is triggered again, and again, and again, ...
这篇关于具有ngrx/效果的无限循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!