gpt4 book ai didi

arrays - 访问对象数组中的特定对象属性时返回对象 promise ? ( Angular - ionic )

转载 作者:行者123 更新时间:2023-12-05 03:41:47 24 4
gpt4 key购买 nike

我有一个对象数组,我希望能够在该数组中的单个对象中提及特定属性。到目前为止我所做的如下:

我将我的对象数组存储在 Ionics 存储中。然后我使用一个异步函数将对象数组分配给我的 typescript 文件中的一个数组:这可以在这里看到;

//The new array
users: User[] = [];

//The async function
async readUsers() {
this.users = await this.service.readUsers();
this.index = this.users.findIndex((x => x.id == this.passed_id));
return this.users[this.index];
}

异步函数将数组分配给 this.users,之后我找到我想要的对象并将其索引分配给 this.index,然后我使用它来标识 this.users 数组中的所需对象。到这里为止的一切都很好,我设法在存储的数组中获取所需的对象。

然后我可以使用以下方法读取所选对象的属性:

“alert(this.users[this.index].firstName)”,而不是异步函数中的最后一行。这也很好用。

但是,现在我想在表单生成器控件中提到一个特定的对象,如下所示:

firstName: [this.readUsers(), Validators.required],

这行不通,返回的都是[Object Promise]。为了从上面提到的对象数组中读取表单输入中的特定属性(作为文本),我可以在这里做什么?感谢您的帮助。

最佳答案

您必须等待 this.readUsers() 以获得解包值。

async method() {
...
firstName: [await this.readUsers(), Validators.required],
...
}

也许对你来说,你必须做这样的事情:

form: any; // using any, but you can change the type to what FormBuilder returns
....
async ngOnInit() {
const users = await this.readusers();
this.form = this.formBuilder.group({
firstName: [users, Validators.required],
});
}

关于arrays - 访问对象数组中的特定对象属性时返回对象 promise ? ( Angular - ionic ),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67609840/

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