javascript - 如何在 Angular 8 中正确使用 setValue

标签 javascript angular

我正在使用 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/

相关文章:

javascript - Meteor 大型应用程序 - 未关闭 <body>

javascript - 如何使用 Javascript 在 Bootstrap 4 上检测屏幕尺寸或查看端口

javascript - module.exports 函数在另一个文件的 require 之后未定义

angular - 是否有 Angular2 View 更新生命周期 Hook ?

angular - 结构指令、位置工具提示

javascript - 更改网页内容上的默认选定文本颜色

javascript - 使用 React Navigation,如何根据嵌套堆栈的屏幕在外部堆栈标题上渲染后退按钮?

angular - 如何为输入字段提供 2 路格式化程序?

javascript - 未捕获异常时的 Angular 中断/暂停

Angular 4验证器同时检查2个控件