如何在与表单结合使用时在同步代码之前运行异步代码。

huangapple go评论78阅读模式
英文:

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});
} 

huangapple
  • 本文由 发表于 2020年1月6日 23:08:56
  • 转载请务必保留本文链接:https://go.coder-hub.com/59614465.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定