I cannot pass the key attribute of the object I want to edit

Asked

Viewed 83 times

1

I’m trying to edit a device inside my CRUD, using Firebase’s Angular 9 and Realtime Database, by clicking on the "Edit" button, I’m redirected to another page so I can change the values of that object, but I’m getting the following console error ERROR Error: Must supply a value for form control with name: 'key'.

I know I need to pass the key value to the form, but I’m not able to do it and I have no idea how to proceed, I’m getting confused

Follows the codes

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)
  }

In case you need any more information, just mention the comments, I am very grateful to those who can help.

  • When does the error appear on the console? do you have any special event? You have the line/method that is popping the error?

  • The exact line that is giving the error is where I opened the <form> tag passing which formGroup it is related to, the 3rd line of HTML from top to bottom, to be more exact

  • Give an assessment on the following: it may be that your editDeviceForm: FormGroup is being instantiated after the this.editDeviceForm.setValue(data); that is in your constructor. If you try to use the setValue before the same instance would occur an error.

1 answer

1

Remove (ngSubmit)="updateDevice()" and add on button

<button mat-raised-button color="primary" (click)="updateDevice()">Atualizar</button>

Test in updateDevice() on Edit.ts with console.log(this.editDeviceForm.value)

The error must be happening in UpdateDevice() device-service, as it is coming indefinitely

Or

It might be this handleError('key', 'required')" that is causing the error as the key is as string:

<mat-error *ngIf="handleError('key', 'required')">
    You must provide a <strong>device number</strong>
</mat-error>
  • I already figured out why I was making that mistake, now another question that arose me, when I am creating a new device, firebase automatically generates the key of the same, however I wanted that key was passed by me, would have some way?

  • 1

    https://firebase.google.com/docs/database/web/read-and-write

  • 1

    https://github.com/angular/angularfire/blob/master/docs/firestore/collections.md

Browser other questions tagged

You are not signed in. Login or sign up in order to post.