订阅 NgRx store returns 空对象

Subscription to the NgRx store returns empty object

我正在尝试开发一个简单的 angular 应用程序,使用 NgRx 来维护状态。

不幸的是,商店订阅的回调被触发,但总是returns一个空对象。

我正在尝试分派对象存储为

this._store.dispatch({
  type: 'ShowPassword',
  payload: value
})

并查看 reducer 函数

export function showPasswordReducer(state, action) {
  //console.log(state);
    switch (action.type) {

    case 'ShowPassword':
      return {
        ...state,
        'ShowPassword': action.payload
      }
    break;
    default:
        return state;
    }
}

我将 StoreModule 的引用添加到根模块的导入数组中作为

StoreModule.forRoot(showPasswordReducer)

并以

的身份订阅商店
this._store.subscribe(val => {
    if (val)
        this.showPassword = val.ShowPassword;
})

Stackblitz link:https://stackblitz.com/edit/angular-first-ngrx-demo

您的代码中缺少几个基本的 NGRX 片段 -

让我们一一处理:

a) 你必须有一个初始状态 [我假设你想要一个跟踪布尔值 showPassword] 的状态。像这样定义一个初始状态对象:

export const initialState = {
  showPassword: false
};

b) 像这样设置你的 reducer 来使用初始状态:

export function showPasswordReducer(state = initialState, action) {
  //console.log(state);
  switch (action.type) {
    case 'ShowPassword':
      return {showPassword: action.payload};
      break;
    default:
      return state;
  }
}

请注意,在默认操作的情况下,reducer 将 return 初始状态。

c) 现在在 forRoot 方法中注入 reducer,状态名称如下:

@NgModule({
  imports: [BrowserModule, FormsModule, StoreModule.forRoot({ShowPassword: showPasswordReducer})],
  declarations: [AppComponent],
  bootstrap: [AppComponent]
})

d) 现在订阅商店 [理想情况下,您必须有选择器 才能从商店获取信息,但为了简单起见,只需直接订阅商店,然后寻找在 forRoot 中使用的相同 属性,如下所示:

ngOnInit() {
    this._store.subscribe(val => {
      console.log(val);
      if (val)
        this.showPassword = val.ShowPassword.showPassword;
    })
  }

工作 stackblitz - https://stackblitz.com/edit/angular-first-ngrx-demo-7yrl2r?file=src/app/app.module.ts

希望对您有所帮助。

您使用的是 ngrx 8,因此您应该接受该语法,我认为它也更简洁。我们现在可以访问 createReducercreateAction。所以我建议如下:

import { createAction, createReducer, on, } from '@ngrx/store';

export const showPwd = createAction(
  'Show Password',
  ({ showPw }: { showPw: boolean }) => ({
    showPw,
  })
)

const initialState = {
  showPw: false
};

export const showPasswordReducer = createReducer(
  initialState.showPw,
    // here you would probably want to have the action(s) in a separate file
    on(this.showPwd, (state: any, action: any) => {
    return action.showPw;
  }),
)

export function reducer(state: any | undefined, action: any) {
  return showPasswordReducer(state, action);
}

然后记得标记到app.module imports:

StoreModule.forRoot({showPwd: showPasswordReducer})

然后最后在您分派操作并收听存储的组件中:

ngOnInit() {
  this._store.subscribe(val => {
    if (val && val.showPwd)
      this.showPassword = val.showPwd;
  })
}

ToggleCheckbox(value: boolean) {
  this._store.dispatch(showPwd({showPw: value}))
}

你的分叉STACKBLITZ