无法在Angular Forms中使用patchValue方法

时间:2018-12-10 07:40:38

标签: angular forms

数据未出现在编辑页面中。我从API那里获得了数据,这些数据我也能够进入service.ts文件,但是我无法在编辑页面上显示它。

  

Edit.customer.ts

import { Component, OnInit } from '@angular/core';
import { CustomerService } from './customer.service';
import { Customer } from '../models/customer.model';
import { FormBuilder, FormGroup, Validators, FormControl } from "@angular/forms";
import { Router } from "@angular/router";
import { first } from "rxjs/operators";

@Component({
  selector: 'app-edit-customer',
  templateUrl: './edit-customer.component.html',
  styleUrls: ['./edit-customer.component.css']
})
export class EditCustomerComponent implements OnInit {

  customer: Customer;
  editForm: FormGroup;

  constructor(private formBuilder: FormBuilder, private router: Router, private _customerService: CustomerService) { }

  ngOnInit() {
    let id = localStorage.getItem("editCustomerId");
    if (!id) {
      alert("Invalid Action")
      this.router.navigate(['list']);
      return;
    }
    this.editForm = this.formBuilder.group({
      customerId: [],
      name: new FormControl('', [Validators.required]),
      email: ['', Validators.required],
      primaryPhone: ['', Validators.required],
      alternatePhone: [''],
      address1: ['', Validators.required],
      address2: ['', Validators.required],
      address3: [''],
      city: ['', Validators.required],
      state: ['', Validators.required],
      country: ['', Validators.required],
      zip: ['', Validators.required],
    });    
    this._customerService.getCustomerById(+id).subscribe(data => {
      this.editForm.patchValue(data);
      console.log(data);
    });
  }
  onSubmit() {
    this._customerService.updateCustomer(this.editForm.value)
      .pipe(first())
      .subscribe(
        data => {
          this.router.navigate(['list']);
        },
        error => {
          alert(error);
        });
  }
}

1 个答案:

答案 0 :(得分:0)

您必须为PatchValue方法定义密钥:

例如。

this.yourform.patchValue({key : "value" });

您也可以使用

动态地执行此操作
this.yourform.patchValue({[key] : [value]});

在您的情况下:

// This is your data from API
var data = {
  name: "Prashant",
  email: "prashantpimpale93@gmail.com"
}

// use the patch value with dynamic keys
Object.keys(data).forEach(key => {
  this.editForm.patchValue({ [key]: data[key] });
})

使用API​​服务中的数据:

this._customerService.getCustomerById(id).subscribe(value => {
  if (value) {
     this.data = value;
  }
});

// Then use patchValue
Object.keys(this.data).forEach(key => {
   this.editForm.patchValue({ [key]: this.data[key] });
})

StackBlitz Example

编辑:

当我检查您的代码时,API正在返回对象列表[不应该],

只需用以下内容替换您的API:

this.userService.getCustomerById(id).subscribe(value => {
  if (value) {
    // the value is an array just get the first item from list
    this.data = value[0];
    Object.keys(this.data).forEach(Key => {
    this.editForm.patchValue({ [Key]: this.data[Key] })
    })
  }
})

我已经在本地环境中进行了测试!