在服务中,我使用此功能从firebase数据库接收所有记录。
treatmentsRef: AngularFireList<any>;
treatments$: Observable<any[]>;
receiveTreatment(){
this.treatmentsRef = this.db.list('/treatments');
this.treatments$ = this.treatmentsRef.valueChanges();
return this.treatments$;
}
接下来,我在组件中调用此函数以填充数组:
treatments= [];
constructor(public dialog: MatDialog, protected CashdeskService: CashdeskService, private formBuilder: FormBuilder, public settings: SettingsService) {
this.settings.receiveTreatment().subscribe( res => this.treatments = res);
console.log(this.treatments);
const formControls = this.treatments.map(control => new FormControl(false));
this.musicForm = this.formBuilder.group({
treatments: new FormArray(formControls)
});
}
当我使用console.log进行订阅时,一切都很好,但是当我尝试订阅this。待遇时,则什么也没有发生。我需要这样做,因为它们的所有处理方式都将显示在动态复选框中,该复选框的结构如下:
<form [formGroup]="musicForm" (ngSubmit)="submit()">
<label formArrayName="treatments" *ngFor="let desc of musicForm.controls.treatments.controls; let i = index" style="width: 100%">
<input type="checkbox" [formControlName]="i">
{{treatments[i].desc}}
</label><br>
<button>submit</button>
</form>
有人知道解决方案吗?或一种基于数组值创建动态列表的简便方法。
答案 0 :(得分:1)
首先,我建议您在ngOnInit()
中而不是在构造函数中进行所有操作,
然后,无论您想使用所订阅的值做什么,都应该在您的subscription()中完成。尝试这样的事情:
ngOnInit(){
this.settings.receiveTreatment().subscribe(
res => {
this.treatments = res
console.log(this.treatments);
const formControls = this.treatments.map(control => new FormControl(false));
this.musicForm = this.formBuilder.group({
treatments: new FormArray(formControls)
});
}
);
}