我正在使用 Angular react 形式。我想使用 setvalue()
使用 API 中的值初始化表单,然后执行更新。我当前正在执行获取请求以获取产品,然后将产品值设置为数据我可以通过将 i
传递给我的函数来实现这一点,然后将其传递给我的服务以通过其 id 获取产品。我从本地主机获取所有数据,所以我没有 stackblitz,因为我不知道它有什么帮助。制作虚拟数据会花费太长时间。如果您需要了解什么,请在评论中告诉我。
我的 update-product.ts 中的函数:
selectedId(id){
this.id = id +1 ;
this.homeService.getProduct(this.id).subscribe(data => {
this.product = data;
});
this.updateProduct.setValue({
id: this.product.id,
productName: this.product.productName,
category: this.product.category.categoryName,
fullPrice: this.product.fullPrice,
salePrice: this.product.salePrice,
availability: this.product.availability,
supplier: this.product.supplier.supplierName,
discount: this.product.discount
});
}
我的表单有三元运算符来跟踪我想要在编辑模式下使用的产品。但我注意到有延迟。在显示数据之前,我必须单击按钮两次。如果我在另一个产品上单击编辑模式,则会显示我选择的上一个产品的产品信息。我相信这是我拥有该功能的地方,但我不确定。
当我点击第二个产品时,会显示第一个产品的数据,我必须总共点击 3 次才能获取当前产品的数据。
最佳答案
您的 setValue() 需要位于您的 subscribe() 内部,否则它将始终在您的 subscribe() 完成之前运行。
selectedId(id){
this.id = id + 1;
this.homeService.getProduct(this.id).subscribe(data => {
this.product = data;
this.updateProduct.setValue({
id: this.product.id,
productName: this.product.productName,
category: this.product.category.categoryName,
fullPrice: this.product.fullPrice,
salePrice: this.product.salePrice,
availability: this.product.availability,
supplier: this.product.supplier.supplierName,
discount: this.product.discount
});
});
console.log(this.id);
}
这可以解释为什么总是需要两次尝试。如果您不确定这是如何工作的,请阅读以下内容: https://angular.io/guide/observables
关于javascript - 如何在 Angular 8 中正确使用 setValue,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58848042/