0

I am having trouble creating an update component that reads the passed in id from the url, makes a get request, and populates a reactive form. I can confirm that the get request is returning what it should in the network tab of the browser.

In my service:

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

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

In my component:

  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);
  }
6
  • I did this one for something else but maybe it will help you stackblitz.com/edit/… also check routing setup Commented Jun 24, 2019 at 17:09
  • 1
    this.getProduct() is asynchronous. You can convert that observable to promise via .toPromise() and use async/await. Or add them into the subscribe. Commented Jun 24, 2019 at 17:12
  • @penleychan, NO. Blake must make the setValues INSIDE subscribe function. FutherMore Blake, you can do this.productForm.setValue(this.product) Commented Jun 24, 2019 at 19:09
  • @Eliseo, Why is that the only option he has to go with doing that? It is valid to do async await. Commented Jun 24, 2019 at 19:29
  • @penleychan I'm sorry, I feel that the way to express my comment was not the most appropriate. I want to say that, in my opinion, it is more natural to use the Observables and subscribe to them. Convert an Observable in Promise is a work around I do not think necessary (Angular work mostly using Observables, not Promise), but it's just an opinion. My apologies if you bothered my comment. Commented Jun 24, 2019 at 19:54

3 Answers 3

2

The problem is you are setting the data to form before it comes from the backend, (subscribe is asynchronous, which means the setvalue functions will execute while the subscribe function is in the process )the best way to do is to trigger the setValue/patch function when the data has arrived from the backend like this

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
});     
     }
   );
  }
Sign up to request clarification or add additional context in comments.

Comments

1

I think you are setting the from before the data is come form server so you should set the form after data come form server as follows:

    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);
         }
       );
      }

Comments

0

you can pathValue wth the value

    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 

                 }
                });

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.