【问题标题】:Trying to edit a object, but the key is not being passed to the form尝试编辑对象,但未将密钥传递给表单
【发布时间】:2020-02-27 14:19:17
【问题描述】:

首先,对于我可能犯的任何英语错误,我深表歉意。

我正在尝试使用 Angular 9 和 Firebase 实时数据库在我的 DataGrid 中编辑一个设备,当我点击“编辑”按钮时,我被重定向到另一个页面,但我得到以下信息错误ERROR Error: Must supply a value for form control with name: 'key'.

我不知道我需要做什么以及如何去做,我真的很困惑。

代码如下:

edit.html

<!-- Device form -->
<div class="inner-wrapper">
  <form [formGroup]="editDeviceForm" (ngSubmit)="updateDevice()" novalidate>
    <mat-card>
      <div class="controlers-wrapper">

        <!-- Device no. -->
        <mat-form-field class="example-full-width">
          <input matInput placeholder="Dispositivo No." formControlName="key">
          <mat-error *ngIf="handleError('key', 'required')">
            You must provide a <strong>device number</strong>
          </mat-error>
        </mat-form-field>

        <!-- Device name -->
        <mat-form-field class="example-full-width">
          <input matInput placeholder="Nome" formControlName="name">
          <mat-error *ngIf="handleError('name', 'required')">
            Você deve fornecer um <strong>nome</strong>
          </mat-error>
        </mat-form-field>

        <!-- Device description -->
        <mat-form-field class="example-full-width">
          <input matInput placeholder="Descrição" formControlName="description">
        </mat-form-field>

        <!-- Device activity -->
        <div class="misc-bottom-padding">
          <mat-label>Atividade: </mat-label>
          <mat-radio-group aria-label="Select an option" formControlName="active">
            <mat-radio-button value="Ativo">Ativo</mat-radio-button>
            <mat-radio-button value="Inativo">Inativo</mat-radio-button>
          </mat-radio-group>
        </div>

        <!-- Route -->
        <mat-form-field class="example-full-width">
          <input matInput placeholder="Rota" formControlName="route">
        </mat-form-field>

        <div class="full-wrapper button-wrapper">
          <div class="button-wrapper">
            <button mat-raised-button color="primary">Atualizar</button>
            <button mat-raised-button type="button" (click)="goBack()">Voltar</button>
          </div>
        </div>
      </div>
    </mat-card>

edit.ts

  visible = true;
  selectable = true;
  removable = true;
  addOnBlur = true;
  editDeviceForm: FormGroup;

  constructor(
    public fb: FormBuilder,
    private location: Location,
    private db: AngularFireDatabase,
    private deviceService: DeviceService,
    private actRoute: ActivatedRoute,
    private router: Router
  ) {
    var id = this.actRoute.snapshot.paramMap.get('id');
    this.deviceService.GetDevice(id).valueChanges().subscribe(data => {
      this.editDeviceForm.setValue(data);
    })
  }

  /* Update form */
  updateDeviceForm() {
    this.editDeviceForm = this.fb.group({
      key: ['', [Validators.required]],
      description: [''],
      active: ['Ativo', [Validators.required]],
      location: [],
      name: ['', [Validators.required]],
      route: ['']
    })
  }

  /* Get errors */
  public handleError = (controlName: string, errorName: string) => {
    return this.editDeviceForm.controls[controlName].hasError(errorName);
  }

  /* Go to previous page */
  goBack() {
    this.location.back();
  }

  /* Submit device */
  updateDevice() {
    var id = this.actRoute.snapshot.paramMap.get('id');
    if (window.confirm('Tem certeza que quer atualizar?')) {
      this.deviceService.UpdateDevice(id, this.editDeviceForm.value);
      this.router.navigate(['devices']);
    }
  }

  ngOnInit() {
    this.updateDeviceForm();
  }

device-service

  devicesRef: AngularFireList<any>;
  deviceRef: AngularFireObject<any>;

  constructor(private db: AngularFireDatabase, private routeService: RouteService) { }

  /* Create device */
  AddDevice(device: Device) {
    this.devicesRef.push({
      key: device.key,
      description: device.description,
      active: device.active,
      name: device.name,
      route: device.route
    })
      .catch(error => {
        this.errorMgmt(error);
      })
  }

  /* Get device */
  GetDevice(id: string) {
    this.deviceRef = this.db.object('/busao/devices/' + id);
    return this.deviceRef;
  }

  /* Get device list */
  GetDeviceList() {
    this.devicesRef = this.db.list('/busao/devices');
    return this.devicesRef;
  }

  /* Update device */
  UpdateDevice(id, device: Device) {
    this.deviceRef.update({
      key: device.key,
      description: device.description,
      active: device.active,
      name: device.name,
      route: device.route
    })
      .catch(error => {
        this.errorMgmt(error);
      })
  }

  /* Delete device */
  DeleteDevice(id: string) {
    this.deviceRef = this.db.object('/busao/devices/' + id);
    this.deviceRef.remove()
      .catch(error => {
        this.errorMgmt(error);
      })
  }

  // Error management
  private errorMgmt(error) {
    console.log(error)
  }

如果您需要更多信息,请在 cmets 上告诉我,如果有人可以帮助我,我将非常感激。

【问题讨论】:

  • 你能定义输入的类型吗?我的意思是:

标签: angular firebase-realtime-database crud


【解决方案1】:

可能是关于 setValue 的使用。 您可以检查您命名为数据的响应是否包含任何键值?

而且我认为这在here 之前已经问过了,请查看相关答案。

  this.deviceService.GetDevice(id).valueChanges().subscribe(data => {
      console.log(data) // TODO: Check the data contains any value for "key" 
      this.editDeviceForm.setValue(data);
    })

【讨论】:

  • 我尝试使用snapshotChanges而不是valueChanges,并且当我使用快照方法时,键值才出现:/
  • @FireZero 如果您解决了问题。我想你可以在这里添加一个答案。
猜你喜欢
  • 1970-01-01
  • 2019-06-06
  • 2014-11-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-23
  • 1970-01-01
相关资源
最近更新 更多