gpt4 book ai didi

angular - 如何确保在以 Angular 渲染 react 形式之前加载可观察数据

转载 作者:行者123 更新时间:2023-12-02 03:38:15 28 4
gpt4 key购买 nike

我正在 Angular 5 应用程序中研究响应式(Reactive)表单、表单组。我通过使用 observable 订阅的 API 获取数据。我的问题是我的 formGroup 尝试在不存在时加载数据并抛出异常。我需要确保 loadData() 在 formGroup 初始化之前加载数据。

组件

export class QuestionsComponent implements OnInit {

@Input() questions: QuestionBase<any>[] = [];
@Input() questionsList: QuestionBase<any>[] = [];
@Input() questionsMappedList: QuestionBase<any>[] = [];
form: FormGroup;

private view: BehaviorSubject<QuestionsDataModel>;
private consultationQuestions: QuestionsDataModel;

constructor(private dataService: QuestionsDataService, private router: Router, private session: SessionStorageService, private qcs: QuestionControlService, private questionService: QuestionMappingService) {

}

ngOnInit(): void {
this.view = new BehaviorSubject<QuestionsDataModel>(null);
this.loadData();
this.questions = this.questionService.getQuestions();
//this.questions = this.questionService.getQuestionList(null);
this.form = this.qcs.toFormGroup(this.questions);
}

public loadData():void
{

//filtersLoaded: Promise<boolean>;

var consultationId = this.session.getItem('consultationId');

this.dataService.getQuestions(consultationId)
.subscribe(data =>{
debugger;
this.view.next(data);
this.questionsList = this.questionService.getQuestionList(data);
console.log("dynamic questionsList...", this.questionsList);

});
}

模板

<div>
<form (ngSubmit)="onSubmit()" [formGroup]="form">

<div *ngFor="let question of questions" class="form-row">
<app-question [question]="question" [form]="form"></app-question>
</div>

<div class="form-row">
<button type="submit" [disabled]="!form.valid">Save</button>
</div>
</form>

<div *ngIf="payLoad" class="form-row">
<strong>Saved the following values</strong><br>{{payLoad}}
</div>
</div>

最佳答案

在 ngOnInit 上添加 bool 条件..

private formData = false;

然后在你的 loadData 函数中执行...

loadData() {

this.formData = true;

然后在你的模板中做..

<form *nGIf='formData'>

或者只是做..

<form *nGIf='myFormDataVariables' >

关于angular - 如何确保在以 Angular 渲染 react 形式之前加载可观察数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49480575/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com