以 observable 作为负载的调度操作

Dispatch action with observable as payload

我有一个 Angular 应用程序,它利用 ngrx/store 来维护应用程序状态。

在我的根组件中,我想分派一个动作来设置侧边栏在状态中的可见性。目前,我的代码如下所示:

export class AppComponent implements OnInit {

  title = 'ye';
  isSidenavVisible$: Observable<boolean>;
  private isSidenavVisible: boolean; // Is this really needed?

  constructor(private store: Store<State>) {
    this.isSidenavVisible$ = this.store.select(getIsSidenavVisible);
  }

  ngOnInit() {
    this.isSidenavVisible$.subscribe(isSidenavVisible => {
      this.isSidenavVisible = isSidenavVisible;
    });
  }

  toggleSidenav() {
    this.store.dispatch(new SetSidenavVisibility(!this.isSidenavVisible));
    // I would like to dispatch the observable as a payload instead
  }
}

尽管这可行,但我想摆脱(在我看来)多余的 private isSidenavVisible 变量,最终能够使用 isSidenavVisible$ 的唯一可观察变量。

初始状态在reducer中设置为true

这是否可能,如果可能,我可以用什么方式进一步简化我的代码?

我没有使用备选 BehaviourSubject 方法,而是选择临时订阅 toggleSidenav() 函数内的可观察对象。

toggleSidenav() {
  this.isSidenavHidden$.first().subscribe(isVisible => {
    this.store.dispatch(new SetSidenavVisibility(!isVisible));
  });
}

结果如愿,不需要私有值变量,而且因为我使用.first()订阅会自动退订。

您不能通过 async 管道将 observable 直接绑定到侧边栏可见性并直接在模板中解析它吗?

使用 async 管道

在边栏模板中绑定可观察对象
export class AppComponent implements OnInit {

  title = 'ye';
  isSidenavVisible$: Observable<boolean>;

  constructor(private store: Store<State>) {
    this.isSidenavVisible$ = this.store.select(getIsSidenavVisible);
  }

  ngOnInit() {
    /* This is not needed because the default value is set in the reducer
    this.isSidenavVisible$.subscribe(isSidenavVisible => {
        this.isSidenavVisible = isSidenavVisible;
    }); */
  }

  toggleSidenav() {
    this.store.dispatch({type: 'TOGGLE_NAVBAR'}); //The logic used to toggle the sidenav is in the reducer
  }
}

在你的模板中是这样的

<div *ngIf="isSidenavVisible$ | async">my content to hide</div>

您必须使用 reducers

toogle 代码可以是这样的:

export const toggleReducer = (state = false, {type, payload}) => { //state = false is the initial condition
  switch(type){
    case TOGGLE_NAVBAR:
      return !state;
    default:
      return state;
  }
}
如果您想查看工作示例,

here 是个笨蛋