[英]Angular populate reactive form with get request in component
我在創建一個更新組件時遇到了麻煩,該組件將從url中讀取傳入的ID,發出一個get請求,並填充一個反應形式。 我可以在瀏覽器的“網絡”標簽中確認get請求正在返回其應有的內容。
為我服務:
productUrl= 'http://localhost:8080/api/products';
getProduct(id: number): Observable<Product> {
const url = `${this.productUrl}/${id}`;
return this.http.get<Product>(url);
}
在我的組件中:
product: Product;
productForm= this.fb.group({
name: ['', Validators.required],
price: ['', Validators.required]
});
ngOnInit() {
this.getProduct();
console.log(this.product);
this.productForm.controls['name'].setValue(this.product.name);
this.productForm.controls['price'].setValue(this.product.price);
}
getProduct(): void {
const id = +this.route.snapshot.paramMap.get('id');
this.productService.getProduct(id)
.subscribe(product=> this.product = product);
}
我認為您是在數據來自表單服務器之前設置表單,因此您應該在數據來自表單服務器之后設置表單,如下所示:
product: Product;
productForm= this.fb.group({
name: ['', Validators.required],
price: ['', Validators.required]
});
ngOnInit() {
this.getProduct();
}
getProduct(): void {
const id = +this.route.snapshot.paramMap.get('id');
this.productService.getProduct(id)
.subscribe(product=> {
this.product = product;
console.log(this.product);
this.productForm.controls['name'].setValue(this.product.name);
this.productForm.controls['price'].setValue(this.product.price);
}
);
}
問題是您要在數據從后端傳入之前進行設置(訂閱是異步的,這意味着setvalue函數將在訂閱函數處於執行狀態時執行),最好的方法是觸發setValue / patch數據從后端這樣到達時起作用
getProduct(): void {
const id = +this.route.snapshot.paramMap.get('id');
this.productService.getProduct(id)
.subscribe(product=> {
this.product = product;
console.log(this.product);
this.productForm.patchValue({
price: this.product.price
name: this.product.name
});
}
);
}
您可以使用值pathValue
this.productService.getProduct(id)
.subscribe(product=> {
this.product = product;
if (this.productForm) {
this.productForm.patchValue(this.product);
// this.productForm.patchValue(this.product, {emitEvent: false}); if you don't want valueChange on form be fired
}
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.