我在尝试订阅依赖于传入Input()
值的组件内部的可观察对象时遇到麻烦。反过来,此值由另一个服务中的BehaviorSubject
设置。
基本上,子组件中的activeForm
从父组件中接收值。父组件又从BehaviorSubject
获取值。因此,该值不是瞬时的。
activeForm
具有属性id
,该属性确定用于另一个服务调用的值,该值我打算在ngOnInit
挂钩中进行。
export class AllFilesComponent implements AfterViewInit, OnInit {
@ViewChild(MatPaginator, { static: false }) paginator: MatPaginator;
@ViewChild(MatSort, { static: false }) sort: MatSort;
@ViewChild(MatTable, { static: false }) table: MatTable<TierData>;
dataSource: AllFilesDataSource;
@Input() activeForm: Form;
ngOnInit() {
// I plan to use the value of property 'id' from activeForm to make the following:
// but if the activeForm is not set yet, this.formId will be undefined!
this.fileService.getDatafilesInForm(this.formId).subscribe(data => {
}
}
我非常有信心,如果我将activeForm
订阅为Observable,然后在其中调用this.fileService.getDatafilesInForm
,那么它会起作用,但看起来并不正确,而且感觉笨拙;我想要一种没有任何反模式的声明式方法。我仍在掌握RxJS,这一直是一项艰巨的挑战,因此不胜感激!
修改 父组件模板
<div class="container" fxLayout="row" fxLayout.xs="column" fxLayoutAlign="center" fxLayoutGap="16px" fxLayoutGap.xs="0"
fxLayoutAlign="start stretch">
<!-- Tree view on LHS-->
<div fxFlex="20%">
<div class="spinner-container" *ngIf="isTreeLoading">
<mat-progress-bar mode="indeterminate"></mat-progress-bar>
</div>
<app-tree-view [TDataSource]="TData"></app-tree-view>
</div>
<div fxFlex fxLayout="column" fxLayoutGap="16px">
<!-- Results table-->
<app-all-files class="mat-elevation-z4" [activeForm]="activeForm"></app-all-files>
<!-- GOOGLE MAP code removed as not relevant to question-->
</div>
</div>
父组件TS:
constructor(private route: ActivatedRoute, private formService: FormService) {
this.activeForm = null;
this.isTreeLoading = true;
this.TData = [{ name: 'loading structure...' }];
}
ngOnInit() {
this.formId = +this.route.snapshot.params['id'];
this.subscriptions = this.formService.currentForm.subscribe(response => {
this.activeForm = response;
if (this.activeForm) {
this.TData = this.formService.generateTreeStructure(this.activeForm);
this.isTreeLoading = false;
}
else {
// this call to the service updates the BehaviorSubject
this.formService.getSingleFormFromAPI(this.formId);
}
});
}