简体   繁体   English

Ngrx state 在 angular 12 中未定义

[英]Ngrx state undefined in angular 12

I am trying to use NGRX redux library with Angular 12. The state of the application is undefined.我正在尝试将 NGRX redux 库与 Angular 12 一起使用。应用程序的 state 未定义。

Index.ts索引.ts

export interface ApplicationState {
  product: ProductState | undefined;
}

export const reducers: ActionReducerMap<ApplicationState> = {
  product: productReducer,
};


export const metaReducers: MetaReducer<ApplicationState>[] = [];

App.module.ts应用模块.ts

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    AppRoutingModule,
    StoreModule.forRoot(reducers, { metaReducers })
    BrowserAnimationsModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

Reducer减速器

export interface ProductState {
  formValidation: FormGroup;
}

export const initialState: ProductState = {
  formValidation: new FormGroup({})
};

export const productReducer: any = (state: ProductState | undefined, incomingAction: Action): ProductState => {
  if (state === undefined) {
    return state;
  }

  const action = incomingAction as KnownAction;
  switch (action.type) {
    case 'FORM_VALIDATION':
      return state;
    default:
      return state;
  }
};

Action行动

export interface ProductFormValidationAction { type: 'FORM_VALIDATION' }

export type KnownAction = ProductFormValidationAction | any;

 export const ActionCreators = {
  formValidation: () => ({ type: 'FORM_VALIDATION' } as ProductFormValidationAction)
};

The state of the application is undefined on the reducer call, quite not sure what may be the main issue.应用程序的 state 在减速器调用中未定义,不太确定可能是主要问题。

Dispatch Method调度方式

import {ActionCreators, GetUsers} from '../../store/action/product.actions'
constructor(
    private store: Store<ApplicationState>
    ) { }

  ngOnInit(): void {
 this.store.dispatch(ActionCreators.formValidation());
  }

You need to default state to your initialState .您需要将state默认为您的initialState

export const proudctReducer = (state: ProductState = initialState, ...)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM