【问题标题】:NGRX reducer not getting triggeredNGRX减速器没有被触发
【发布时间】: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
    };
  })
);

【问题讨论】:

    标签: angular ngrx


    【解决方案1】:

    我想你在注册reducer时只需要对app.module.ts稍作改动

    StoreModule.forRoot({ app: appReducer })
    

    StackBlitz

    【讨论】:

      猜你喜欢
      • 2018-04-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-03-12
      • 2015-01-11
      • 1970-01-01
      • 1970-01-01
      • 2018-10-27
      相关资源
      最近更新 更多