angular2和rxjs:ngIf根据主题

时间:2017-03-30 07:34:34

标签: angular rxjs

我已创建此Subject

private componentsState$: Subject<{[key: string]: boolean}> = new Subject();

我正在使用async管道订阅我的模板:

<div *ngIf="(componentsState$ | async).list" payment-list></div>
<div *ngIf="(componentsState$ | async).form" payment-form></div>
<div *ngIf="(componentsState$ | async).detail" payment-detail></div>

payment-listpayment-formpayment-detail是子组件,根据componentsState$主题彼此交换。

on onNgInit

ngOnInit(): void {
  this.swapToList();
}

swapToList(): void {
  this.swapComponent('list');
}

swapComponent(componentName: string): void {
  let componentsState = {
    'list': (): void => this.componentsState$.next(this.getListComponentState()),
    'form': (): void => this.componentsState$.next(this.getFormComponentState()),
    'detail': (): void => this.componentsState$.next(this.getDetailComponentState()),,
  };

  componentsState[componentName]();
}

getListComponentState,返回key: boolean对象:

private getListComponentState(): {[key: string]: boolean} {
  return { list: true, form: false, detail: false};
}

getFormComponentState

private getFormComponentState(): {[key: string]: boolean} {
  return { list: false, form: true, detail: false};
}

getDetailComponentState

private getDetailComponentState(): {[key: string]: boolean} {
  return { list: false, form: false, detail: true};
}

然而,渲染模板时会显示任何组件。有什么想法吗?

我要说,它只是第一次加载组件父组件时才会失败。

1 个答案:

答案 0 :(得分:1)

我已使用BehaviorSubject代替Subject解决了问题:

private componentsState$: BehaviorSubject<{[key: string]: boolean}> = new BehaviorSubject(this.getListComponentState());

因此,我可以设置初始值,并避免在next()方法上调用onNgInit