订阅NgRx存储将返回空对象

时间:2019-09-11 11:38:08

标签: angular ngrx ngrx-store state-management

我正在尝试使用y[5]=101, y2[7] = 103 ; x[5] = 405 , x2[3] = 402来维护状态的简单角度应用程序。

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

我正在尝试分发对象以将其存储为

NgRx

看一看reduce函数

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

我在根模块的imports数组中添加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)

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

2 个答案:

答案 0 :(得分:1)

您的代码中缺少一些基本的NGRX片段-

让我们一一对应:

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

export const initialState = {
  showPassword: false
};

b)设置减速器以利用如下初始状态:

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

请注意,如果使用默认操作,reducer将返回初始状态。

c)现在在forRoot方法中以如下状态名称注入化径器:

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

正在工作的堆叠闪电战-https://stackblitz.com/edit/angular-first-ngrx-demo-7yrl2r?file=src/app/app.module.ts

希望有帮助。

答案 1 :(得分:1)

您正在使用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