NGRX减速器未触发

时间:2020-10-13 20:31:02

标签: angular ngrx

我正在Angular 10应用程序中实现NGRX,似乎在调用reducer时遇到了问题。我在应用程序组件中创建了一个复选框。我试图保持它的切换状态。我创建了一个动作和减速器。我不确定为什么没有调用减速器。我在reducer中写了一个console.log,它似乎没有触发。我没有使用过强的动作名称类型,但是确保名称匹配。

应用模块

@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>

应用组件

 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
    };
  })
);

1 个答案:

答案 0 :(得分:0)

我认为您在注册reducer时只需要对app.module.ts进行一点更改

StoreModule.forRoot({ app: appReducer })

StackBlitz