Угловой 7: проблема при попытке использовать метод метода в компоненте - PullRequest
0 голосов
/ 19 марта 2019

Я пытаюсь научиться использовать Angular 7. Я следую руководству на его официальном сайте, и теперь я хочу создать форму, чтобы попытаться рассчитать фискальный код (только для итальянцев).Пользователь вставит данные для его вычисления, и когда вы начнете вводить свой фискальный код, программа в фоновом режиме начнет его вычислять, и, когда они будут равны, в форме будет напечатано сообщение «Правильно» или что-то в этом роде.Я сделал сервис, чтобы выполнить расчет и проверить его с помощью специального валидатора, получить запрос на определенный URL для получения кода города.Проблема заключается в следующем: когда я пытаюсь вызвать метод службы в компоненте, он возвращает эту ошибку «ОШИБКА TypeError: Невозможно прочитать свойство« json »из undefined».У кого-нибудь из вас есть решение?

КОМПОНЕНТНЫЙ КОД:

    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 КОМПОНЕНТНЫЙ КОД:

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

СЕРВИСНЫЙ КОД:

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

Ответы [ 2 ]

0 голосов
/ 19 марта 2019

Чтобы получить доступ к свойству this.json , вы должны инициализировать его, как вы это сделали с codice, sucesso, а затем скопировать его в свой конструктор

constructor(private json: JsonService) { this.json = json; }
0 голосов
/ 19 марта 2019

Для меня это выглядит как контекстная ошибка (т. Е. Ваше ключевое слово this больше не ссылается на ваш компонент).

Это обычно происходит, когда вы связываете функцию с другой или используете сокращенный синтаксис для выполнения вызова.

Попробуйте, расскажите, как это происходит:

Validator :

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

Функция :

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
      }
    }
  }
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...