可以在this stackblitz中解决该问题。
该示例很简单:用户选择种族和专业。
我希望当选择比赛时,将专业重置(ed?)。
为此,我创建了一个效果:
@Effect()
raceChange = this.actions
.pipe(
ofType(SET_RACE),
mapTo(new SetSpecialtyAction(''))
);
但是操作未添加到流中。有人可以解释一下为什么吗? (我是@ngrx的新手,所以请彻底!)
PS:我知道我可以使用the solution from my previous question,但是我正在尝试学习ngrx基础知识。
stackblitz组件的代码:
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.raceStore.select('race');
currentSpecialty = this.specStore.select('specialty');
constructor(
public raceStore: Store<RaceState>,
public specStore: Store<SpecialtyState>,
) {
this.currentRace.subscribe(x => console.log('race : ', x));
this.currentSpecialty.subscribe(x => console.log('spec : ', x))
}
dispatchRace(race) {
this.raceStore.dispatch(new SetRaceAction(race));
}
dispatchSpecialty(spec) {
this.specStore.dispatch(new SetSpecialtyAction(spec));
}
}
export const SET_RACE = '[RACE] Set';
export 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 RaceState {
readonly race: string;
}
export interface SpecialtyState {
readonly specialty: string;
}
答案 0 :(得分:1)
mapTo
将发射映射到字符串,使用map
将映射到将调度的动作。
为了使您的示例有效,我做了两件事:
1-实际上,将mapTo
替换为map
:
@Effect()
raceChange = this.actions
.pipe(
ofType(SET_RACE),
map(() => new SetSpecialtyAction(''))
);
2-更改忽略空值的减速器:
export function specialtyReducer(state: string = undefined, action: SetSpecialtyAction): string {
return action.specialty;
}
const value = '' || 'Not Empty';
console.log(value);
您还可以使用switchMap
映射到多个动作,并为动作返回一个数组:
@Effect()
raceChange = this.actions
.pipe(
ofType(SET_RACE),
switchMap(() => [new SetSpecialtyAction(''), ...])
);
答案 1 :(得分:0)
不需要效果,您可以收听专业减速器中的赛车动作:
export function specialtyReducer(state: string = undefined, action: SetSpecialtyAction | SetRaceAction): string {
switch(action.type) {
case SET_RACE:
return '';
default:
return action.specialty || state;
}
}