繁体   English   中英

角填充响应形式与组件中的获取请求

[英]Angular populate reactive form with get request in component

我在创建一个更新组件时遇到了麻烦,该组件将从url中读取传入的ID,发出一个get请求,并填充一个反应形式。 我可以在浏览器的“网络”标签中确认get请求正在返回其应有的内容。

为我服务:

productUrl= 'http://localhost:8080/api/products';

  getProduct(id: number): Observable<Product> {
    const url = `${this.productUrl}/${id}`;
    return this.http.get<Product>(url);
  }

在我的组件中:

  product: Product;

  productForm= this.fb.group({
    name: ['', Validators.required],
    price: ['', Validators.required]
  });

  ngOnInit() {
    this.getProduct();
    console.log(this.product);

    this.productForm.controls['name'].setValue(this.product.name);
    this.productForm.controls['price'].setValue(this.product.price);
  }

  getProduct(): void {
    const id = +this.route.snapshot.paramMap.get('id');
    this.productService.getProduct(id)
      .subscribe(product=> this.product = product);
  }

我认为您是在数据来自表单服务器之前设置表单,因此您应该在数据来自表单服务器之后设置表单,如下所示:

    product: Product;

      productForm= this.fb.group({
        name: ['', Validators.required],
        price: ['', Validators.required]
      });

      ngOnInit() {
        this.getProduct();

      }

      getProduct(): void {
        const id = +this.route.snapshot.paramMap.get('id');
        this.productService.getProduct(id)
          .subscribe(product=> {
           this.product = product;
           console.log(this.product);

           this.productForm.controls['name'].setValue(this.product.name);
           this.productForm.controls['price'].setValue(this.product.price);
         }
       );
      }

问题是您要在数据从后端传入之前进行设置(订阅是异步的,这意味着setvalue函数将在订阅函数处于执行状态时执行),最好的方法是触发setValue / patch数据从后端这样到达时起作用

getProduct(): void {
const id = +this.route.snapshot.paramMap.get('id');
this.productService.getProduct(id)
      .subscribe(product=> {
       this.product = product;
       console.log(this.product);
       this.productForm.patchValue({
price: this.product.price
name: this.product.name
});     
     }
   );
  }

您可以使用值pathValue

    this.productService.getProduct(id)
      .subscribe(product=> { 
                 this.product = product;
                 if (this.productForm) {
                     this.productForm.patchValue(this.product); 
                     //  this.productForm.patchValue(this.product, {emitEvent: false}); if you don't want valueChange on form be fired 

                 }
                });

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM