我正在使用角度7的redux。我可以将值添加到状态中。但是我该如何订阅状态的更改值。
这是我尝试过的代码
选择器
export const selectProfessionalLearningTeacherFeature =
createFeatureSelector<any>('professionalLearningTeacher');
export const selectProfessionalLearningTeachers =
createSelector(selectProfessionalLearningTeacherFeature, (state) => state.professionalLearningTeacher);
运动组件
@Component({
selector: 'app-sports-practice',
templateUrl: './sports-practice.component.html',
styleUrls: ['./sports-practice.component.scss']
})
export class SportsPracticeComponent implements OnInit {
constructor(private fb: FormBuilder, private professionalLearningService: ProfessionalLearningService,private _store: Store<any>) {
this._store.select(selectProfessionalLearningTeachers)
.pipe(takeUntil(this._ngOnDestroy)).subscribe(item => {
console.log(item);
});
}
ngOnInit() { }
}
这是我的减速器组件
const meta: any = '';
const ProfessionalLearningTeachers: any = '';
const INITIAL_STATE: any = {
meta,
ProfessionalLearningTeachers
}
export function ProfessionalLearningTeacherReducer() {
return function entityReducer(
state: any = INITIAL_STATE,
a: Action,
): any {
const action = a as EntityAPIAction;
if (!action.meta) {
return state;
}
let itemIndex = -1;
switch (action.type) {
case ProfessionalLearningTeacherApiActions.PROFESSIONAL_LEARNING_TEACHER_SAVE_SUCCEEDED:
return storeProfessionalLearning(state, action);
}
return state;
};
}
function storeProfessionalLearning(state, action): any {
return Object.assign({}, state, {
meta: action.meta,
ProfessionalLearningTeachers: action.payload,
});
}
状态图
控制台输出
参考
In angular (v5) how do I listen to my apps Redux state object changing?
https://github.com/angular-redux/store/blob/master/articles/select-pattern.md
答案 0 :(得分:0)
您可以使用选择器。
professionalLearningTeacher.selectors.ts:
import { createFeatureSelector, createSelector } from '@ngrx/store';
export const selectProfessionalLearningTeacherFeature =
createFeatureSelector<ProfessionalLearningTeacherState | any>('professionalLearningTeacher');
// 'professionalLearningTeacher' is bad practice, this should be a const
export const selectProfessionalLearningTeachers =
createSelector(selectProfessionalLearningTeacherFeature, (state) => state.professionalLearningTeachers);
portsPracticeComponent.ts:
@Component({
selector: 'app-sports-practice',
templateUrl: './sports-practice.component.html',
styleUrls: ['./sports-practice.component.scss']
})
export class SportsPracticeComponent implements OnInit {
professionalLearningTeachers$: Observable<any>;
constructor(
private _store: Store<IAppState>
) {
}
ngOnInit() {
this.professionalLearningTeachers = this._store.select(selectProfessionalLearningTeachers)
.pipe(takeUntil(this._ngOnDestroy));
}
}
请注意: