Angular 7:尝试在组件中使用方法服务时出现问题 [英] Angular 7 : problem while trying to using a method service in a component

查看:62
本文介绍了Angular 7:尝试在组件中使用方法服务时出现问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试学习如何使用Angular7.我遵循他的官方网站上的指南,现在我想制作一张表格来尝试计算财务代码(仅适用于意大利人).用户将插入数据以进行计算,并且当您开始键入财务代码时,程序将在后台开始计算它,并且当它们相等时,表格将在消息上盖章显示:正确"或类似内容.我提供了一项服务来进行计算,并使用自定义验证器对其进行验证,并获得对特定URL的获取请求以检索城市代码.问题是:当我尝试在组件中调用服务的方法时,它将返回此错误错误TypeError:无法读取未定义的属性'json'".你们中的某人有解决方案吗?

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?

组件代码:

    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)

推荐答案

在我看来,这是一个上下文错误(即您的 this 关键字不再引用您的组件).

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 :

验证器:

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

这篇关于Angular 7:尝试在组件中使用方法服务时出现问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆