Angular 7 : problem while trying to using a method service in a component

旧时模样 提交于 2021-01-28 16:44:30

问题


I'm trying to learn how to use Angular 7. I follow the guide on his official site and now I want to do a Form for try to calculate the fiscal code ( for italian people only ). The user will insert the data for calculate it and when you start to type your fiscal code the program in background start to calculate it and when they are equal the form will stamp a message that say: "Right" or something like that. I made a service to do the calculation and validate it with a custom validator a get request to a specific URL for retrieve the city code. The problem is: when i try to call the method of the service in the component it return this error " ERROR TypeError: Cannot read property 'json' of undefined ". Some one of you have the solution?

COMPONENT CODE :

    import { Component, OnInit } from '@angular/core';
import { FormControl, Validators, FormGroup, AbstractControl } from '@angular/forms';
import { citta } from '../country';
import { validazioneData } from '../validatorCustom';
import { JsonService } from '../json.service';


@Component({
  selector: 'app-form',
  templateUrl: './form.component.html',
  styleUrls: ['./form.component.css']
})


export class FormComponent implements OnInit {

  codice: any;

  successo = false;

  cities = citta;

  mioForm: FormGroup;

  invioForm() {
    if (this.mioForm.valid)
      this.successo = true;
  }

  constructor(private json: JsonService) { }

  ngOnInit() {
    this.mioForm = new FormGroup({

      nome: new FormControl('', [Validators.required, Validators.maxLength(10), Validators.minLength(3)]),
      cognome: new FormControl('', [Validators.required, Validators.maxLength(10), Validators.minLength(3)]),
      sesso: new FormControl('', Validators.required),
      dataDiNascita: new FormControl('', [Validators.required, validazioneData]),
      citta: new FormControl('Catanzaro', Validators.required),
      codiceFiscale: new FormControl('', [Validators.required,  this.validatoreCf])

    });
  }

  validatoreCf(control: AbstractControl): { [key: string]: any } | null {
    if (control && (control.value !== null && control.value !== undefined && control.value !== "" && isNaN(control.value))) {

      this.codice = this.json.getCF(control);

      if (this.codice === control.root.get('codiceFiscale').value.toString().trim().toUpperCase()) {
        return null;
      }

      return {
        validCF: true
      }
    }
  }
}

HTML COMPONENT CODE :

<h1>MIO FROM</h1>


<form (ngSubmit)='invioForm()' [formGroup]="mioForm">


  <label>
    Nome:
    <input type="text" formControlName="nome" placeholder="Inserisci il nome">
    <!-- ERRORI Data -->
    <div *ngIf="mioForm.get('nome').hasError('required') && mioForm.get('nome').touched">
      Nome Richiesto!
    </div>
    <div *ngIf="mioForm.get('nome').hasError('minlength') || mioForm.get('nome').hasError('maxlength')">
      La lunghezza deve essere compresa tra i 2 e i 12 caratteri!
    </div>
  </label>

  <label>
    Cognome:
    <input type="text" formControlName="cognome" placeholder="Inserisci il cognome">
    <!-- ERRORI Data -->
    <div *ngIf="mioForm.get('cognome').hasError('required') && mioForm.get('cognome').touched">
      Cognome Richiesto!
    </div>
    <div *ngIf="mioForm.get('cognome').hasError('minlength') || mioForm.get('cognome').hasError('maxlength')">
      La lunghezza deve essere compresa tra i 2 e i 12 caratteri!
    </div>
  </label>

  <label>
    Sesso:
    <select formControlName="sesso">
      <option value="M">M</option>
      <option value="F">F</option>
    </select>
    <!-- ERRORI Data -->
    <div *ngIf="mioForm.get('sesso').hasError('required') && mioForm.get('sesso').touched">
      Sesso Richiesto!
    </div>
  </label>
  <br>

  <label>
    Data di nascita:
    <input type="date" formControlName="dataDiNascita">
    <!-- ERRORI Data -->
    <div *ngIf="mioForm.get('dataDiNascita').hasError('required') && mioForm.get('dataDiNascita').touched">
      Data di nascita Richiesta!
    </div>
    <div *ngIf="mioForm.get('dataDiNascita').hasError('validData')">
      Data di nascita non valida!
    </div>
  </label>

  <label>
    Città:
    <select formControlName="citta">
      <option *ngFor="let c of cities" value="{{c.nome}}">{{c.nome}}</option>
    </select>
    <!-- ERRORI Data -->
    <div *ngIf="mioForm.get('citta').hasError('required') && mioForm.get('citta').touched">
      Citta Richiesta!
    </div>
  </label>

  <label>
    CODICE FISCALE:
    <input type="text" formControlName="codiceFiscale">
    <div *ngIf="mioForm.get('codiceFiscale').hasError('validCF') && mioForm.get('codiceFiscale').touched">Errore</div>
  </label>

  <div>
    <button>submit</button>
  </div>


</form>
<br>

<p *ngIf="successo">

  BRAVISSIMO
</p>

SERVICE CODE :

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { AbstractControl } from '@angular/forms';
import { mesi, charDispari, charPari, finale } from './costanteCF';

@Injectable({
  providedIn: 'root'
})

export class JsonService {

  constructor(private http: HttpClient) { }

  //Validazione codice fiscale
  getCF(control : AbstractControl) {
     console.log(control);
      let codice: string = "";
      var pt1: string;
      var pt2: string;
      var pt3: string;
      var pt4: string;
      var pt5: string;
      var cf: string;

      if ((control.root.get('cognome') !== null || undefined) && control.root.get('nome') !== null && control.root.get('citta') !== null && control.root.get('dataDiNascita') !== null && control.root.get('sesso') !== null){

        pt1 = this.primaPT(control.root.get('cognome').value);
        pt2 = this.secondaPT(control.root.get('nome').value);
        pt3 = this.terzaPT(control.root.get('dataDiNascita').value, control.root.get('sesso').value);
        pt4 = this.quartaPT(control.root.get('citta').value);
        pt5 = this.quintaPT(cf);

          codice = pt1 + pt2 + pt3 + pt4 + pt5;

        return codice.toString().trim().toUpperCase();
      }
    }

    getCCC(nomeCitta: any): String {

      let risultato: any;

      this.http.get('http://www.gerriquez.com/comuni/ws.php?dencomune='+nomeCitta).subscribe(dato => risultato = dato);

      console.log(risultato);

      risultato = JSON.parse(risultato);

      risultato = risultato.CodiceCatastaleDelComune.value;

      console.log("ciao"+risultato);

      return risultato;
    };


  //quarta parte relativa alla citta
  quartaPT(citta: any): string {

    let http: HttpClient;

    //let form = new FormComponent(http);

    if (citta !== undefined && citta !== null && citta !== "")
      citta = this.getCCC(citta);

    return citta;
  }



  //Ultima lettera
  quintaPT(cf: any): string {

    if (cf !== undefined && cf !== null && cf !== "") {

      let dispari = charDispari;

      let pari = charPari;

      let finali = finale;

      let somma: number;
      let carattereFinale: string;
      let ar = cf.split('');

      for (var i = 0; i < ar.length; i++) {
        if ((i % 2) === 0) {
          for (let a of dispari) {
            if (a.n1 === (ar[i])) {
              somma = somma + a.n2;
            }
          }
        }
      }

      for (var i = 0; i < ar.length; i++) {
        if ((i % 2) === 1) {
          for (let a of pari) {
            if (a.n1 === (ar[i])) {
              somma = somma + a.n2;
            }
          }
        }
      }

      for (let a of finali) {
        if ((somma % 26) === a.n2) {
          carattereFinale = a.n1;
        }
      }


      return carattereFinale;
    }
    return "";
  }







  //Terza parte relativa alla datra di nascita
  terzaPT(dataDiNascita: any, sesso: any): string {

    if (dataDiNascita && sesso !== undefined && dataDiNascita && sesso !== null && dataDiNascita && sesso !== "") {

      let listaMesi = mesi;

      let data: any = new Date(dataDiNascita);

      dataDiNascita.toString();

      dataDiNascita = '';

      dataDiNascita += data.getFullYear();

      let mese = data.getMonth();
      for (let a of listaMesi) {
        if (mese === a.Mese) {
          mese = a.lettera.toString();
          dataDiNascita += mese;
        }
      }

      let giorno = data.getDay();

      if (sesso.toUpperCase() === 'F')
        giorno = giorno + 40;

      dataDiNascita += giorno;

      return dataDiNascita;
    }
    return "";
  }









  //Seconda parte relativa al nome
  secondaPT(nome: any): string {

    if (nome !== undefined && nome !== null && nome !== "") {
      nome = nome.trim().toUpperCase();

      if (nome.length < 3) {
        let ar = nome.split('');
        if (ar.length === 2) {
          ar.push('X');
          return ar.toString();
        }

        ar.push('X');
        ar.push('X');
        return ar.toString();
      }

      let cont = 0;
      let ar = nome.split('');
      console.log(ar);
      nome = '';

      for (var i = 0; i < ar.length; i++) {
        if (nome.length < 3 && (ar[i] !== 'A' && ar[i] !== 'E' && ar[i] !== 'I' && ar[i] !== 'O' && ar[i] !== 'U')) {
          if (cont !== 1) {
            nome += ar[i];
            cont++;
            ar[i] = null;
          }
        }
      }

      if (nome.length < 3) {
        for (var i = 0; i < ar.length; i++) {
          if (ar[i] !== null) {
            nome += ar[i];
            ar[i] = null;
          }
        }
      }

      return nome;

    }
    return "";
  }


  //Prima parte relativa al cognome
  primaPT(cognome: any): string {


    if (cognome !== undefined && cognome !== null && cognome !== "") {
      cognome = cognome.trim().toUpperCase();

      if (cognome.length < 3) {
        let ar = cognome.split('');
        if (ar.length === 2) {
          ar.push('X');
          return ar.toString();
        }

        ar.push('X');
        ar.push('X');
        return ar.toString();
      }

      let ar = cognome.split('');
      console.log(ar);
      cognome = '';


      for (var i = 0; i <= ar.length; i++) {
        if (cognome.length < 3) {
          if (ar[i] !== 'A' && ar[i] !== 'E' && ar[i] !== 'I' && ar[i] !== 'O' && ar[i] !== 'U') {
            cognome += ar[i];
          }
        }
      }

      return cognome;
    }
    return "";
  }

}

ERROR CODE :

  ERROR TypeError: Cannot read property 'json' of undefined
    at push../src/app/form/form.component.ts.FormComponent.validatoreCf (form.component.ts:48)
    at forms.js:658
    at Array.map (<anonymous>)
    at _executeValidators (forms.js:658)
    at forms.js:623
    at forms.js:658
    at Array.map (<anonymous>)
    at _executeValidators (forms.js:658)
    at FormControl.validator (forms.js:623)
    at FormControl.push../node_modules/@angular/forms/fesm5/forms.js.AbstractControl._runValidator (forms.js:2914)

回答1:


Seems like a context error to me (i.e. your this keyword doesn't reference your component anymore).

This usually happens when you bind a function to another or use a shortened syntax to make the call.

Try this, tell me how it goes :

Validator :

codiceFiscale: new FormControl('', [Validators.required,  this.validatoreCf()])

Function :

validatoreCf() {

  return (control: AbstractControl): { [key: string]: any } | null {
    if (control && (control.value !== null && control.value !== undefined && control.value !== "" && isNaN(control.value))) {

      this.codice = this.json.getCF(control);

      if (this.codice === control.root.get('codiceFiscale').value.toString().trim().toUpperCase()) {
        return null;
      }

      return {
        validCF: true
      }
    }
  }
}



回答2:


In order to access this.json property, you have to initialize it, just like you did with codice, sucesso, and then instance it on your constructor

constructor(private json: JsonService) { this.json = json; }


来源:https://stackoverflow.com/questions/55243579/angular-7-problem-while-trying-to-using-a-method-service-in-a-component

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!