我在创建一个更新组件时遇到了麻烦,该组件从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);
}
答案 0 :(得分:1)
我认为您是在数据来自表单服务器之前设置from,因此您应该在数据来自表单服务器之后设置表单,如下所示:
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);
}
);
}
答案 1 :(得分:1)
问题是您要在数据从后端传入之前进行设置(订阅是异步的,这意味着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
});
}
);
}
答案 2 :(得分:0)
您可以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
}
});