1

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

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

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

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

看看减速器功能

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 链接:https ://stackblitz.com/edit/angular-first-ngrx-demo

4

2 回答 2

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

于 2019-09-11T13:04:58.523 回答
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) 现在在方法中注入 reducer,forRoot状态名称如下:

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

d) 现在订阅 store [理想情况下,您必须有选择器来从 store 获取信息,但为了简单起见,只需直接订阅 store 并查找与下面使用的相同的属性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

希望能帮助到你。

于 2019-09-11T12:27:21.313 回答