[英]Angular 2 how to handle asynchronous calls
第一次以未定义形式单击按钮将返回,必须单击两次按钮才能返回正确的结果。 返回结果后如何处理? 单击按钮后返回正确的结果不是上一个?
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;
}
以此方式在Product.compontent.ts中修改onSubmit() :
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 => this.product = product
。 它将product
分配给this.product
,但是在该程序执行其他代码之前,该代码位于.subscribe(product => this.product = product)
您需要做的就是将observable传递给HTML并使用| async
获得值| async
| async
管道。
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>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.