英文:
how to run async code before sync code in combination with form
问题
迄今为止,我有一个表单,可以在 indexedDB 中保存一些数据(例如姓名列表),并将它们显示为列表。当我点击列表中的条目时,会打开另一个表单,我可以在其中编辑我点击的姓名。第二个表单应该与第一个表单完全相同,只是输入部分不为空,而是填充了我点击的姓名。
我的表单需要同步代码(据我所知):
myForm = new FormGroup({
name: new FormControl('', [Validators.required])
});
我的第一个尝试是:
ngOnInit() {
db.list.get({ id: 1 }, temp => this.names = temp);
this.myForm.patchValue({ name: this.names.name });
}
但是 get
是异步的,并且在 patchValue
之后解析,所以什么也不会发生。
所以我尝试了:
ngOnInit() {
db.list.get({ id: 1 }).then(function (names) {
this.myForm.patchValue({ name: names.name });
});
}
但是这时候 myForm
是未知的,如果我在那一点声明 myForm
,我的表单会不高兴,因为它没有被声明。
现在我已经没有更多的想法了。
有人知道如何解决这个问题吗?
英文:
so far I have a form, where I could save some data in an indexedDB (e.g. a list of names) and display them as a list. When I click on the entry of that list another form opens, where I can edit the name I've clicked on. the second form should exactly look like the first one except that the input section isn't empty but filled with the name I've clicked on.
my Form needs sync code (as far as I know)
myForm = new Formgroup({
name: newFormControl('',[Validators.required])
});
my first try was:
ngOnInit() {
db.list.get({id: 1}, temp => this.names = temp);
this.myForm.patchValue({name: this.names.name});
}
but get is async and resolves after patchValue so nothing happens.
So I've tried:
ngOnInit() {
db.list.get({id: 1}).then( function(names){
this.myForm.patchValue({name: names.name});
});
}
but then myForm is unknown an if I declare myForm at that point my Form is unhappy because it's not declared.
Now I`ve run out of ideas.
Does anyone know how to solve this?
答案1
得分: 2
你可以尝试使用await
关键字
async ngOnInit() {
const value = await db.list.get({id: 1}, temp => this.names = temp);
this.myForm.patchValue({name: this.value.name});
}
英文:
You can try using the await
keyword
async ngOnInit() {
const value = await db.list.get({id: 1}, temp => this.names = temp);
this.myForm.patchValue({name: this.value.name});
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论