我有 3 个组件 inquiry-form
、inquiry-response
和 inquiry-summary
在某些情况下,这个组件可以隐藏和显示,我使用 rxjs
subject
在组件之间发送数据,这是场景:
查询表格
- 有2个分区
- 用户输入 id 号(重定向到查询响应 1),它将隐藏查询表单上的 2 div
查询-响应
- 有 2-div
- 更改 ID 按钮重定向到查询表 1
- 选中复选框并提交按钮重定向到查询摘要 2
这里我创建了stackblitz这就是我尝试过的:
inquiry-store.service.ts
private hideContainer = new Subject<boolean>();
public hideContainer$ = this.hideContainer.asObservable
();
private summary = new Subject<boolean>();
public summary$ = this.summary.asObservable
();
private checkbox = new Subject<boolean>();
public checkbox$ = this.checkbox.asObservable
();
setHideContainer(data: boolean) {
this.hideContainer.next(data);
}
setSummary(data: boolean) {
this.summary.next(data);
}
setCheckbox(data: boolean) {
this.checkbox.next(data);
}
}
并且在每个组件中都会根据条件订阅它,
inquiry-form.component.ts
ngOnInit() {
this.inquiryStore.hideContainer$.subscribe(istrue => {
this.isHasSummon = istrue;
});
}
onSubmit(): void {
this.inquiryService.getData(data).subscribe((res: any)=> {
this.inquiryStore.setSummon(res);
this.isHasSummon = true;
})
}
inquiry-response.component.ts
ngOnInit() {
this.inquiryStore.hideContainer$.subscribe(isTrue => {
this.showChangeId = isTrue;
});
this.inquiryStore.checkbox$.subscribe(isTrue => {
this.hideCheckbox = isTrue;
})
}
submitSelectedCheckbox() {
this.inquiryStore.setSummary(false)
this.hideCheckbox = true;
}
goToInquiryForm() {
this.inquiryStore.setHideContainer(false);
this.isShowResponse = false;
}
}
我遇到了一些问题,在查询响应 1 中,点击更改 ID 后,它将重定向到查询表单 1,单击提交按钮后,它不会再次进入查询响应 1,是否有更好的方法来做到这一点?
最佳答案
inquiry-store.service.ts
public formState = new Subject<boolean>();
public responseState = new Subject<boolean>();
inquiry-form.component.ts
isHasSummon = false;
ngOnInit() {
this.inqueryStore.formState.subscribe(res => {this.isHasSummon = res});
}
onSubmit() {
this.isHasSummon = true;
this.inqueryStore.responseState.next(true);
}
inquiry-response.component.ts
isShowResponse = false;
ngOnInit() {
this.inqueryStore.responseState.subscribe(res => {this.isShowResponse = res});
}
goToInquiryForm() {
this.isShowResponse = false;
this.inqueryStore.formState.next(true);
}
试试这个。您可以使用相同的模式来显示和隐藏摘要部分
我为此创建了两个新的公共(public)主题。但这不是强制性的。您使用了很好的方法来封装主题。你可以使用那种方式,我这样做只是为了简单。希望这会奏效。
关于javascript - 使用 rxjs subject 在 Angular 7 中显示和隐藏组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57918664/