Erstmalige Schaltfläche wird in Form angeklickt, undefined ist zurück, Schaltfläche muss zweimal geklickt werden, um korrektes Ergebnis zurückzugeben. Wie verarbeite ich nicht, bis das Ergebnis zurückkommt? Wenn die Schaltfläche geklickt wurde, geben Sie das korrekte Ergebnis und nicht das vorherige zurück.Angular 2, wie mit asynchronen Aufrufen umzugehen ist
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;
}
}
}
}
Produkt-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;
}
wo ist deine Form? Ich sehe nicht einmal in Ihrem html –
Mögliches Duplikat von [Wie gebe ich die Antwort von einem Observable/http/async-Aufruf in angular2 zurück?] (Http://stackoverflow.com/questions/43055706/how-do- i-return-the-response-von-beobachtbar-http-async-call-in-angular2) – Alex