简体   繁体   中英

Angular 2 how to handle asynchronous calls

First time button is clicked in form undefined is return, button has to be clicked twice to return correct result. How do I not process until result is return. When button clicked return correct result not previous one?

Product.componet.html

 <div *ngIf="submitted">
    <h2>Product found</h2>
    <div class="row">
        <div class="col-xs-3">Price</div>
        <div class="col-xs-9  pull-left">Product details</div>
        <div class="col-xs-3">{{ product.price }}</div>
        <div class="col-xs-9  pull-left">{{product.description}}</div>
    </div>
</div>
<div *ngIf="result">
    <h2>No Product found</h2>
</div>

Product.compontent.ts

onSubmit() {
    if (this.formModel.valid) {
        this.submitted = false;
        this.result = false;

        lens id = this.formModel.controls['id'].value;

        this.productService.getProductOne(id)
            .subscribe(product => this.product = product)

        //Check to see if object undefined
        if (this.product) {                
            if (this.product.id != 0)
            {
                this.submitted = true;
            }
            else    
            {
                this.result = true;
            }                
        }
    }
}

product-service.ts

  getProductOne(id: number): Observable<Product> {
      // Parameters obj
      let params: URLSearchParams = new URLSearchParams();
      params.set('id', id.toString());

      //Http request
      return this.http
          .get("api/getProduct", {
              search: params
          })
          .map(response => response.json())
          .catch(handleError);
  }

Web api – ProductController.cs

 [Route("api/getProduct")]
    public Product GetProduct(int id)
    {
        var product = products.FirstOrDefault((p) => p.id == id);

        if (product == null)
        {
            product = new Product();
        }

        return product;
    }

Modify your onSubmit() in Product.compontent.ts this way :

onSubmit() {
        if (this.formModel.valid) {
            this.submitted = false;
            this.result = false;

            lens id = this.formModel.controls['id'].value;

            this.productService.getProductOne(id).subscribe(
                    (product) => {
                     this.product = product;
                        //Check to see if object undefined
                        if (this.product) {                
                            if (this.product.id != 0)
                            {
                                this.submitted = true;
                            }
                            else    
                            {
                                this.result = true;
                            }                
                        }
              });
        }
    }

This happens because of this product => this.product = product . It assign product into this.product ,but before that program executes other codes which are after the .subscribe(product => this.product = product)

what you need to do is just pass the observable to HTML and get values using | async | async pipe.like this.

Product.compontent.ts

  products: any;
  onSubmit() {
    if (this.formModel.valid) {
      this.submitted = false;
      this.result = false;

      lens id = this.formModel.controls['id'].value;
      this.products = this.productService.getProductOne(id);
    }
  }  

Product.componet.html

<div [hidden]="!(products|async)?.id !=0">
  <h2>Product found</h2>
  <div class="row">
    <div class="col-xs-3">Price</div>
    <div class="col-xs-9  pull-left">Product details</div>
    <div class="col-xs-3">{{(products|async)?.price }}</div>
    <div class="col-xs-9  pull-left">{{(products|async)?.description }}</div>
  </div>
</div>
<div [hidden]="!(products|async)?.id ==0">
  <h2>No Product found</h2>
</div>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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