NgRx:将一个事件从商店分发到另一个 [英] NgRx : dispatch one event from a store to another
问题描述
我开始使用@ngrx,并且遇到了一个似乎无法找到答案的问题.
I'm beginning to use @ngrx and I'm facing an issue to which I can't seem to find an answer.
我在此stackblitz 中进行了说明>:当玩家选择比赛时,应将专长重新设置为undefined.
I illustrated it in this stackblitz : when a player picks a race, the specialty should be set back to undefined.
起初,我以为我可以使用异径管,但没有注射就不了解这家商店.
At first I thought I could use the reducer, but it doesn't have knowledge of the store without injection.
我应该如何解决此问题?
(注意:这是一个可复制的示例,我知道我可以在函数中添加第二个调度.我想要的是自动执行)
How should I approach this issue ?
(Note : this is a reproductible example, I know I can put a second dispatch in my functions. What I want is to do it automatically)
相关代码:
import { Component } from '@angular/core';
import { Store, Action, ActionReducerMap } from '@ngrx/store';
@Component({
selector: 'my-app',
template:
`
<select #race (change)="dispatchRace(race.value)" placeholder="Select a race">
<option value="Elf">Elf</option>
<option value="Orc">Orc</option>
<option value="Dwarf">Dwarf</option>
</select>
<select #spec (change)="dispatchSpecialty(spec.value)" placeholder="Select a specialty">
<option value="Warrior">Warrior</option>
<option value="Berzerkrer">Berzerkrer</option>
<option value="Healer">Healer</option>
</select>
<p>
Current race: {{ (currentRace | async) || 'None' }}
</p>
<p>
Current Spec: {{ (currentSpecialty | async) || 'None' }}
</p>
`
})
export class AppComponent {
currentRace = this.store.select('race');
currentSpecialty = this.store.select('specialty');
constructor(public store: Store<CharacterState>) { }
dispatchRace(race) {
this.store.dispatch(new SetRaceAction(race));
}
dispatchSpecialty(spec) {
this.store.dispatch(new SetSpecialtyAction(spec));
}
}
const SET_RACE = '[RACE] Set';
const SET_SPECIALTY = '[CLASS] Set';
export class SetRaceAction implements Action {
readonly type = SET_RACE;
constructor(public race: string) { }
}
export class SetSpecialtyAction implements Action {
readonly type = SET_SPECIALTY;
constructor(public specialty: string) { }
}
export function raceReducer(state: string = undefined, action: SetRaceAction): string {
return action.race || state;
}
export function specialtyReducer(state: string = undefined, action: SetSpecialtyAction): string {
return action.specialty || state;
}
export interface CharacterState {
readonly race: string;
readonly specialty: string;
}
推荐答案
如果在raceReducer
中添加console.log
,则可以看到所有动作都由所有reducer处理:
If you add a console.log
in the raceReducer
you can see that all the actions are handled by all the reducers :
export function raceReducer(state: string = undefined, action: SetRaceAction): string {
console.log(action);
return action.race || state;
}
您只需要以不同的方式处理SetRaceAction
和SetSpecialtyAction
.
You just need to handle SetRaceAction
and SetSpecialtyAction
differently.
这篇关于NgRx:将一个事件从商店分发到另一个的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!