具有可观察的有效负载的调度操作

时间:2017-10-04 11:54:03

标签: angular redux rxjs ngrx ngrx-effects

我有一个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

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

3 个答案:

答案 0 :(得分:0)

我选择暂时订阅BehaviourSubject函数中的observable,而不是使用替代toggleSidenav()方法。

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

结果符合要求,不需要私有值变量,因为我使用.first()订阅将自动取消订阅。

答案 1 :(得分:0)

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

答案 2 :(得分:0)

使用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就是那个人。

相关问题