猿问

Angular 在组件中使用 get 请求填充反应形式

我在创建一个更新组件时遇到问题,该组件从 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);

  }


有只小跳蛙
浏览 194回答 3
3回答

一只名叫tom的猫

你可以pathValue用价值&nbsp; &nbsp; this.productService.getProduct(id)&nbsp; &nbsp; &nbsp; .subscribe(product=> {&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;this.product = product;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;if (this.productForm) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;this.productForm.patchValue(this.product);&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;//&nbsp; this.productForm.patchValue(this.product, {emitEvent: false}); if you don't want valueChange on form be fired&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;}&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; });
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答