【发布时间】:2020-10-13 20:31:02
【问题描述】:
我正在我的 Angular 10 应用程序中实现 NGRX,但调用减速器似乎有问题。我在应用程序组件中创建了一个复选框。我试图保持它的切换状态。我创建了一个动作和减速器。我不确定为什么减速器没有被调用。我在减速器中编写了一个似乎没有触发的 console.log。我没有使用强类型的动作名称,但确保名称匹配。
app.module
@NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule,
AppRoutingModule,
StoreModule.forRoot(appReducer, {})
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
app.component.html
<input type="checkbox" id="checkMe" (change)="checkChanged()" [checked]="displayCode" />
<label for="checkMe">Check Me</label>
app.component
export class AppComponent implements OnInit {
title = 'Angular-NGRX-Practice';
displayCode: boolean;
constructor(private store: Store<any>) {
}
ngOnInit(): void {
this.store.select('app').subscribe(
app => {
if (app) {
this.displayCode = app.showCheck;
}
});
}
checkChanged(): void {
console.log('check changed fired!!!');
this.store.dispatch(
{ type: '[App] Toggle Check box' }
);
}
}
app.reducer
import { createAction, createReducer, on } from '@ngrx/store';
export const appReducer = createReducer({ showCheck: true },
on(createAction('[App] Toggle Check box'), state => {
console.log('Original State: showCheck', JSON.stringify(state));
return {
...state,
showCheck: !state.showCheck
};
})
);
【问题讨论】: