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

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

问题描述

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

组件代码:

 import { Component, OnInit } from '@angular/core';从@angular/forms"导入 { FormControl, Validators, FormGroup, AbstractControl };从'../country'导入{citta};从'../validatorCustom'导入{validazioneData};从 '../json.service' 导入 { JsonService };@成分({选择器:'应用程序',templateUrl: './form.component.html',styleUrls: ['./form.component.css']})导出类 FormComponent 实现 OnInit {代码:任何;后继=假;城市 = 心;mioForm:表单组;invioForm() {如果(this.mioForm.valid)this.successo = true;}构造函数(私有 json:JsonService){}ngOnInit() {this.mioForm = new FormGroup({名称: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 } |空值 {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()) {返回空;}返回 {有效CF:真}}}}

HTML 组件代码:

MIO FROM

<form (ngSubmit)='invioForm()' [formGroup]="mioForm"><标签>姓名:<input type="text" formControlName="nome" placeholder="Inserisci il nome"><!-- 错误数据--><div *ngIf="mioForm.get('nome').hasError('required') && mioForm.get('nome').touched">没有里奇斯托!

<div *ngIf="mioForm.get('nome').hasError('minlength') || mioForm.get('nome').hasError('maxlength')">La Lunghezza deve essere compresa tra i 2 e i 12 caratteri!

<标签>认知:<input type="text" formControlName="cognome" placeholder="Inserisci il cognome"><!-- 错误数据--><div *ngIf="mioForm.get('cognome').hasError('required') && mioForm.get('cognome').touched">Cognome Richiesto!

<div *ngIf="mioForm.get('cognome').hasError('minlength') || mioForm.get('cognome').hasError('maxlength')">La Lunghezza deve essere compresa tra i 2 e i 12 caratteri!

<标签>塞索:<select formControlName="sesso"><option value="M">M</option><option value="F">F</option></选择><!-- 错误数据--><div *ngIf="mioForm.get('sesso').hasError('required') && mioForm.get('sesso').touched">塞索·里奇斯托!

<br><标签>数据 di nascita:<input type="date" formControlName="dataDiNascita"><!-- 错误数据--><div *ngIf="mioForm.get('dataDiNascita').hasError('required') &&mioForm.get('dataDiNascita').touched">数据 di nascita Richiesta!

<div *ngIf="mioForm.get('dataDiNascita').hasError('validData')">Data di nascita non valida!

<标签>心:<select formControlName="citta"><option *ngFor="let c of城市" value="{{c.nome}}">{{c.nome}}</option></选择><!-- 错误数据--><div *ngIf="mioForm.get('citta').hasError('required') && mioForm.get('citta').touched">西塔里奇斯塔!

<标签>法典财政:<input type="text" formControlName="codiceFiscale"><div *ngIf="mioForm.get('codiceFiscale').hasError('validCF') &&mioForm.get('codiceFiscale').touched">Errore</div><div><按钮>提交

</表单><br><p *ngIf="successo">布拉维西莫</p>

服务代码:

import { Injectable } from '@angular/core';从'@angular/common/http' 导入 { HttpClient };从'@angular/forms' 导入 { AbstractControl };导入 { mesi, charDispari, charPari, finale } from './costanteCF';@Injectable({提供在:'根'})导出类 JsonService {构造函数(私有http:HttpClient){}//Validazione 法典财政getCF(控制:抽象控制){控制台日志(控制);让代码:字符串=";var pt1:字符串;var pt2:字符串;var pt3:字符串;var pt4:字符串;var pt5:字符串;var cf: 字符串;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);代码 = pt1 + pt2 + pt3 + pt4 + pt5;返回 codice.toString().trim().toUpperCase();}}getCCC(nomeCitta: any): 字符串 {让 risultato: 任何;this.http.get('http://www.gerriquez.com/comuni/ws.php?dencomune='+nomeCitta).subscribe(dato => risultato = dato);控制台.log(risultato);risultato = JSON.parse(risultato);risultato = risultato.CodiceCatastaleDelComune.value;console.log("ciao"+risultato);返回 risultato;};//quarta parte relativa alla cittaquartaPT(citta: any): 字符串 {让 http: HttpClient;//let form = new FormComponent(http);if (citta !== undefined && citta !== null && citta !== "")citta = this.getCCC(citta);还心;}//最后一封信quintaPT(cf: any): 字符串 {if (cf !== undefined && cf !== null && cf !== "") {让 dispari = charDispari;让 pari = charPari;让 finali = 结局;让 somma:数字;让 carattereFinale: 字符串;让 ar = cf.split('');for (var i = 0; i < ar.length; i++) {如果 ((i % 2) === 0) {对于(让一个不同的){如果 (a.n1 === (ar[i])) {somma = somma + a.n2;}}}}for (var i = 0; i < ar.length; i++) {如果 ((i % 2) === 1) {for (let a of pari) {如果 (a.n1 === (ar[i])) {somma = somma + a.n2;}}}}for (let a of finali) {if ((somma % 26) === a.n2) {carattereFinale = a.n1;}}返回 carattereFinal;}返回 "";}//Terza parte relativa alla datra di nascitaterzaPT(dataDiNascita: any, sesso: any): 字符串 {if (dataDiNascita && sesso !== undefined && dataDiNascita && sesso !== null && dataDiNascita && sesso !== "") {让 listaMesi = mesi;让数据:any = new Date(dataDiNascita);dataDiNascita.toString();数据DiNascita = '';dataDiNascita += data.getFullYear();让 mese = data.getMonth();for (let a of listaMesi) {if (mese === a.Mese) {mese = a.lettera.toString();dataDiNascita += mese;}}让 giorno = data.getDay();如果 (sesso.toUpperCase() === 'F')乔诺 = 乔诺 + 40;dataDiNascita += giorno;返回数据DiNascita;}返回 "";}//Seconda parte relativa al nomesecondaPT(名称:任何):字符串{if (nome !== undefined && nome !== null && nome !== "") {nome = nome.trim().toUpperCase();如果(名称.长度<3){让 ar = nome.split('');如果(ar.length === 2){ar.push('X');返回 ar.toString();}ar.push('X');ar.push('X');返回 ar.toString();}让连续 = 0;让 ar = nome.split('');控制台日志(ar);名称 = '';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')) {如果(继续!== 1){名称 += ar[i];续++;ar[i] = 空;}}}如果(名称.长度<3){for (var i = 0; i < ar.length; i++) {如果 (ar[i] !== null) {名称 += ar[i];ar[i] = 空;}}}返回名称;}返回 "";}//Prima parte relativa al cognomeprimaPT(cognome: any): 字符串 {if (cognome !== undefined && cognome !== null && cognome !== "") {cognome = cognome.trim().toUpperCase();如果(cognome.length <3){让 ar = cognome.split('');如果(ar.length === 2){ar.push('X');返回 ar.toString();}ar.push('X');ar.push('X');返回 ar.toString();}让 ar = cognome.split('');控制台日志(ar);科诺姆 = '';for (var i = 0; i <= ar.length; i++) {如果(cognome.length <3){if (ar[i] !== 'A' && ar[i] !== 'E' && ar[i] !== 'I' && ar[i] !== 'O' && ar[i] !== 'U') {认知 += ar[i];}}}返回认知;}返回 "";}}

错误代码:

 错误类型错误:无法读取未定义的属性json"在 push../src/app/form/form.component.ts.FormComponent.validatoreCf (form.component.ts:48)在 forms.js:658在 Array.map (<匿名>)在 _executeValidators (forms.js:658)在 forms.js:623在 forms.js:658在 Array.map (<匿名>)在 _executeValidators (forms.js:658)在 FormControl.validator (forms.js:623)在 FormControl.push../node_modules/@angular/forms/fesm5/forms.js.AbstractControl._runValidator (forms.js:2914)

解决方案

对我来说似乎是上下文错误(即您的 this 关键字不再引用您的组件).

当您将一个函数绑定到另一个函数或使用缩短的语法进行调用时,通常会发生这种情况.

试试这个,告诉我结果如何:

验证器:

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

功能:

validatoreCf() {return (control: AbstractControl): { [key: string]: any } |空值 {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()) {返回空;}返回 {有效CF:真}}}}

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)

解决方案

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

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

查看全文
相关文章
其他开发最新文章
热门教程
热门工具
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆