我已创建此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-list
,payment-form
和payment-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};
}
然而,渲染模板时会显示任何组件。有什么想法吗?
我要说,它只是第一次加载组件父组件时才会失败。
答案 0 :(得分:1)
我已使用BehaviorSubject
代替Subject
解决了问题:
private componentsState$: BehaviorSubject<{[key: string]: boolean}> = new BehaviorSubject(this.getListComponentState());
因此,我可以设置初始值,并避免在next()
方法上调用onNgInit
。