第一次按下按鈕的形式是undefined就是返回,按鈕必須點擊兩次才能返回正確的結果。在結果返回之前我如何不處理。當按鈕點擊返回正確的結果不是前一個?Angular 2如何處理異步調用
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;
}
}
}
}
產品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;
}
哪裏是你的形式?我甚至沒有在您的html中看到一個 –
[我如何從angular2中的Observable/http/async調用返回響應?](http://stackoverflow.com/questions/43055706/how-do- I-返回的響應從 - 一個可觀測-HTTP-異步-通話中angular2) – Alex