我是 Angular 的新手。在這里,我試圖將一個物件添加到資料庫并同時在模板中顯示它。
app.component.ts
export class AppComponent implements OnInit {
title = 'HttpRequest';
allProducts: Product[] = [];
@ViewChild('productsForm')
form!: NgForm;
constructor(private http: HttpClient) {}
ngOnInit() {
this.fetchProducts();
}
onProductsFetch() {
this.fetchProducts();
}
onProductCreate(products: { pName: string; desc: string; price: string }) {
console.log(products);
let header = new HttpHeaders({ myHeader: 'sachin' });
this.http
.post<{ name: string }>(
'*****',
JSON.stringify(products),
{ headers: header }
)
.subscribe({
next: (res) => {
// console.log(res);
},
});
//--------------------Error is here-----------------------------------------
//! This is not working
this.onProductsFetch();
//! This is working
// setTimeout(() => {
// this.onProductsFetch();
// }, 1000);
//--------------------Error is here-----------------------------------------
}
private fetchProducts() {
this.http
.get<{ [key: string]: Product }>(
'*****'
)
.pipe(
map((res) => {
let products: Product[] = [];
for (const [key, value] of Object.entries(res)) {
products.push({ ...value, id: key });
}
return products;
})
)
.subscribe({
next: (products) => {
this.allProducts = [...products];
console.log(this.allProducts);
},
});
}
}
app.component.html
<div class="main-area">
<div class="content-area">
<div class="header">
<h1>Manage Products</h1>
<hr />
</div>
<div class="container">
<!--Add product form-->
<div class="form-area">
<h3>Create Product</h3>
<form
#productsForm="ngForm"
(ngSubmit)="onProductCreate(productsForm.value)"
>
<label>Procuct Name</label>
<input type="text" name="pName" ngModel />
<label>Procuct Description</label>
<input type="text" name="desc" ngModel />
<label>Procuct Price</label>
<input type="text" name="price" ngModel />
<input type="submit" value="Add Product" />
</form>
</div>
<!--Display product area-->
<div class="product-display-area">
<h3>All Products</h3>
<table id="products">
<tr>
<th>#</th>
<th>Name</th>
<th>Description</th>
<th>Price</th>
<th></th>
<th></th>
</tr>
<tr *ngFor="let prod of allProducts; let i = index">
<td>{{ i 1 }}</td>
<td>{{ prod.pName }}</td>
<td>{{ prod.desc }}</td>
<td>${{ prod.price }}</td>
</tr>
</table>
<hr />
<div class="action-btn-container">
<button class="btn-fetch" (click)="onProductsFetch()">
Refresh Products
</button>
</div>
</div>
</div>
</div>
</div>
產品.model.ts
export class Product {
pName!: string;
desc!: string;
price!: string;
id?: string;
}
所以在這里,當我使用 onProductCreate() 方法時,POST 方法正在作業,但 onProductFetch() 不起作用,并且模板沒有更新,而如果我們使用 setTimeout(),它完全作業并且模板也得到了更新。為什么會這樣?
PS:如果我的問題是錯誤的,請原諒我:)
uj5u.com熱心網友回復:
http.post只是立即回傳 observable 并且不等待您的 POST 得到回應。
你必須把你this.onProductsFetch();的subscribe。
this.http
.post<{ name: string }>(
'******',
JSON.stringify(products),
{ headers: header }
)
.subscribe({
next: (res) => {
// console.log(res);
this.onProductsFetch();
},
});
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/515576.html
上一篇:如何根據兩個屬性獲取不同的值
下一篇:如何手動撰寫打字稿宣告檔案?
