Javascript 如何将setValue正确用于Angular 8
我用的是角度反应形式。我想使用Javascript 如何将setValue正确用于Angular 8,javascript,angular,Javascript,Angular,我用的是角度反应形式。我想使用setvalue()使用API中的值初始化表单,然后执行更新。我当前正在执行获取产品的get请求,然后我将产品值设置为从我的服务中获取的数据。我可以通过将I传递给我的函数来实现这一点,然后将该函数传递给我的服务,以根据其id获取产品。I我从本地主机获取所有数据,所以我没有stackblitz,因为我不知道这会有什么帮助。制作虚拟数据需要很长时间。如果您需要了解任何信息,请在评论中告诉我 my update-product.ts中的函数: selectedId(id)
setvalue()
使用API中的值初始化表单,然后执行更新。我当前正在执行获取产品的get请求,然后我将产品值设置为从我的服务中获取的数据。我可以通过将I
传递给我的函数来实现这一点,然后将该函数传递给我的服务,以根据其id获取产品。I我从本地主机获取所有数据,所以我没有stackblitz,因为我不知道这会有什么帮助。制作虚拟数据需要很长时间。如果您需要了解任何信息,请在评论中告诉我
my 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
});
}
我的表单有三元运算符,用于跟踪在编辑模式下需要的产品。但我注意到有一个延迟。在显示数据之前,我必须单击按钮两次。如果我在另一个产品上单击“编辑模式”,则会显示我选择的上一个产品的产品信息。我相信这是我的功能所在,但我不确定
当我点击第二个产品时,会显示第一个产品的数据,我必须总共点击三次才能从当前产品中获取数据。如果您不想使用ngrx,更好的方法是为您的编辑模式创建行为主题 editStarted=新行为主体(false); editItemChanged=新行为主体({}) 在您的服务类中创建此服务,并根据需要随时订阅。
所以,一旦editStarted或editItemChanged通过在其上envoking next()触发,组件就会收到通知,并可以执行您想要执行的任何代码。如果您不想使用ngrx,更好的方法是为editMode创建行为主题 editStarted=新行为主体(false); editItemChanged=新行为主体({}) 在您的服务类中创建此服务,并根据需要随时订阅。 因此,一旦editStarted或editItemChanged通过在其上envoking next()触发,组件就会收到通知,并可以执行您想要执行的任何代码。您的设置值()需要位于订阅()内部,否则它总是在订阅()完成之前运行
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);
}
这就解释了为什么总是需要两次尝试。如果您不确定其工作原理,请阅读:
您的设置值()必须位于订阅()的内部,否则它总是在订阅()完成之前运行
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);
}
这就解释了为什么总是需要两次尝试。如果您不确定其工作原理,请阅读:
一般来说,最好将这些文件上的代码缩短一点。这个问题相当吓人。一般来说,在这些问题上把代码缩短一点是个好主意。这个问题很吓人。