ВыражениеChangedAfterItHasBeenCheckedError angular 4 в 2020 - PullRequest
0 голосов
/ 09 января 2020

я знаю, что на эту ошибку были даны ответы в разных вопросах, я уже пытался использовать AfterViewInit и ChangeDetectorRef, но не могу обработать ошибку.

client-sign-ups.component.ts

import {Component, OnInit,AfterViewInit,ChangeDetectorRef} from '@angular/core';
import {User} from '../../../common/user/models/user.model';
import {ErrorInterceptorService} from '../../../common/error/error.service';
import {UserService} from '../../../common/user/services/user.service';
import {ActivatedRoute, Router} from '@angular/router';
import {UserSignUpService} from "../../../common/user/services/register.service";



@Component({
  selector: 'app-client-sign-up-home',
  templateUrl: './client-sign-up.component.html',
  styleUrls: ['./client-sign-up.component.scss']
})
export class ClientSignUpComponent implements OnInit {

  user: User;
  terms: boolean;
  policy: boolean;
  error: Error;
  success = false;

  constructor(private router: Router,
              private route: ActivatedRoute,
              private errorInterceptorService: ErrorInterceptorService,
              private userService: UserService,
              private userSignUpService: UserSignUpService,
              private cd:ChangeDetectorRef) {
    this.userSignUpService.userSignUp.subscribe(user => this.user = user);
    this.errorInterceptorService.errorObservable.subscribe(err => this.error = err);
  }

  ngOnInit() {
    if (!this.user) {
      this.user = new User(User.CLIENT);
    }
  }
  ngAfterViewInit() {
    this.cd.detectChanges();
}
  notValid() {
    let error = {
      name: 'Formulario no válido',
      message: ''
    };

    let ans = true;

    if (this.user.name) {
      if (this.user.name.length === 0) {
        error.message += error.message === '' ? 'Nombre no válido' : ', Nombre no válido';
        ans = false
      }
    } else ans = false;

    if (this.user.phoneNumber) {
      if (isNaN(Number(this.user.phoneNumber)) || this.user.phoneNumber.length < 9) {
        error.message += error.message === '' ? 'Teléfono no válido' : ', Teléfono no válido';
        ans = false
      }
    } else ans = false;

    if (this.user.email) {
      this.user.email = this.user.email.toLowerCase();
      if (this.user.email.split('@').length !== 2 || !this.user.email.split('@')[1].includes('.') || this.user.email.includes(" ")) {
        error.message += error.message === '' ? 'Correo no válido' : ', Correo no válido';
        ans = false
      }
    } else ans = false;

    if (this.user.password) {
      if (!this.checkPassword(this.user.password)) {
        //error.message += error.message === '' ? 'La clave debe contener minimo 8 caracteres, con una mayuscula, una minuscula, un numero y un caracter especial. Los caracteres especiales aceptados son: ^ $ * . [ ] { } ( ) ? - " ! @ # % & / \\ \, \> \< \' : ; | _ ~ `' : ', La clave debe contener minimo 8 caracteres, con una mayuscula, una minuscula, un numero y un caracter especial. Los caracteres especiales aceptados son: ^ $ * . [ ] { } ( ) ? - " ! @ # % & / \\ \, \> \< \' : ; | _ ~ `';
        error.message += error.message === '' ? 'La clave debe contener minimo 8 caracteres, con una mayuscula, una minuscula, un número.' : ', La clave debe contener minimo 8 caracteres, con una mayuscula, una minuscula, un número.';
        ans = false
      }
    } else ans = false;

    if (this.user.confirmPassword) {
      if (this.user.confirmPassword.length === 0)
        ans = false
    } else ans = false;

    if (this.user.password && this.user.confirmPassword) {
      if (this.user.password !== this.user.confirmPassword) {
        error.message += error.message === '' ? 'La clave de confirmación no concuerda' : ', La clave de confirmación no concuerda'
        ans = false
      }
    } else ans = false;

    if (!this.terms) ans = false;
    if (!this.policy) ans = false;

    if (error.message !== '') this.error = error;
    else delete this.error;

    return ans;
  }

  signUpUser() {
    this.user.email = (this.user.email && this.user.email.trim()) || '';
    if (!this.user.email && this.user.email.length > 0) {
      this.error = {
        name: 'NotValidMail',
        message: 'Correo no válido'
      }
    }

    this.user.username = this.user.email;

    this.userService.signUp(this.user).subscribe(user => {
      this.success = true;
    });
  }

  checkPassword(passwd:string) {
    let numbers = /[0-9]/g;
    let upperCaseLetters = /[A-Z]/g;
    let lowerCaseLetters = /[a-z]/g;
    //let specialCharacters = /(\^|\$|\*|\.|\[|\]|\{|\}|\(|\)|\?|\-|\"|\!|\@|\#|\%|\&|\/|\\|\,|\>|\<|\'|\:|\;|\||\_|\~|\`)/g;
    //if (passwd.match(numbers) && passwd.match(upperCaseLetters) && passwd.match(lowerCaseLetters) && passwd.match(specialCharacters) && passwd.length >= 8)
    if (passwd.match(numbers) && passwd.match(upperCaseLetters) && passwd.match(lowerCaseLetters) && passwd.length >= 8)
      return true;
    return false;
  }

  topPage() {
    document.body.scrollTop = 0;
    document.documentElement.scrollTop = 0;
  }
}

client-sign-up.component. html

<h3 class="card-title" i18n>Registro del cliente
  <small>{{ user.username }}</small>
</h3>

<form *ngIf="!success">
  <div class="form-group row">
    <label class="col-sm-4 form-control-label" i18n>Correo <label style="color: red">*</label></label>
    <div class="col-sm-8">
      <input type="email" class="form-control" [(ngModel)]="user.email" [ngModelOptions]="{standalone: true}"
             placeholder="Correo">
    </div>
  </div>

  <div class="form-group row">
    <label class="col-sm-4 form-control-label" i18n>Nombre <label style="color: red">*</label></label>
    <div class="col-sm-8">
      <input type="text" class="form-control" [(ngModel)]="user.name" [ngModelOptions]="{standalone: true}"
             placeholder="Nombre">
    </div>
  </div>

  <div class="form-group row">
    <label class="col-sm-4 form-control-label" i18n>Apellidos <label style="color: red">*</label></label>
    <div class="col-sm-8">
      <input type="text" class="form-control" [(ngModel)]="user.familyName" [ngModelOptions]="{standalone: true}"
             placeholder="Apellidos">
    </div>
  </div>

  <div class="form-group row">
    <label class="col-sm-4 form-control-label" i18n>Teléfono <label style="color: red">*</label></label>
    <div class="col-sm-8 input-group">
      <div class="input-group-addon">+57</div>
      <input type="text" class="form-control" [(ngModel)]="user.phoneNumber" [ngModelOptions]="{standalone: true}"
             placeholder="Teléfono">
    </div>
  </div>

  <div class="form-group row">
    <label class="col-sm-4 form-control-label" i18n>Clave <label style="color: red">*</label></label>
    <div class="col-sm-8">
      <input type="password" class="form-control" [(ngModel)]="user.password" [ngModelOptions]="{standalone: true}"
        placeholder="Clave" pattern="(?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?=.*(\^|\$|\*|\.|\[|\]|\{|\}|\(|\)|\?|\-|\u0022|\!|\@|\#|\%|\&|\/|\\|\,|\>|\<|\'|\:|\;|\||\_|\~|\`)).{8,}">
    </div>
  </div>

  <div class="form-group row">
    <label class="col-sm-4 form-control-label" i18n>Confirmar Clave<label style="color: red">*</label></label>
    <div class="col-sm-8">

      <input type="password" class="form-control" [(ngModel)]="user.confirmPassword" [ngModelOptions]="{standalone: true}"
             placeholder="Confirmar Clave">
    </div>
  </div>


  <div class="alert alert-danger" *ngIf="error" role="alert" i18n >{{ error.message }} s </div>

  <div class="form-check">
    <input type="checkbox" id="Check1" [(ngModel)]="terms" [ngModelOptions]="{standalone: true}"/>
    <label class="form-check-label" for="Check1"><a [routerLink]="'/terms-conditions'" target="_blank" (click)="topPage()">Términos y
        Condiciones</a></label>
  </div>
  <div class="form-check">
    <input type="checkbox" id="Check2" [(ngModel)]="policy" [ngModelOptions]="{standalone: true}">
    <label class="form-check-label" for="Check2"><a [routerLink]="'/privacy-policy'" target="_blank" (click)="topPage()">Políticas de
        Privacidad</a></label>
  </div>

  <div class="text-right">
    <button class="btn btn-primary btn-block" [disabled]="!notValid()" (click)="signUpUser()" i18n>Registrarse</button>
  </div>
</form>

<div *ngIf="success">
  <div class="alert alert-success" role="alert" i18n>
    El usuario {{ user.username }} ha sido registrado exitosamente. El código de confirmación deberá llegar a tu teléfono {{ user.phoneNumber }} pronto.
  </div>

  <div class="card-block">
    <div class="text-right">
      <a class="k-button k-primary" [routerLink]="'../confirm/' + user.username" i18n>Confirmar usuario</a>
    </div>
  </div>

</div>

это моя ошибка

ERROR Error: ExpressionChangedAfterItHasBeenCheckedError: Expression has changed after it was checked. Previous value: 'UsernameExistsException: User already exists'. Current value: 'undefined'.
    at viewDebugError (core.es5.js:8507)
    at expressionChangedAfterItHasBeenCheckedError (core.es5.js:8485)
    at checkBindingNoChanges (core.es5.js:8649)
    at checkNoChangesNodeInline (core.es5.js:12502)
    at checkNoChangesNode (core.es5.js:12476)
    at debugCheckNoChangesNode (core.es5.js:13251)
    at debugCheckDirectivesFn (core.es5.js:13153)
    at Object.eval [as updateDirectives] (ClientSignUpComponent.html:51)
    at Object.debugUpdateDirectives [as updateDirectives] (core.es5.js:13135)
    at checkNoChangesView (core.es5.js:12296)

я при попытке показать сообщение о том, что электронная почта уже существует, поскольку cognito возвращает эту информацию, она отображается в теге ошибки на html в течение 1 секунды (только если я помещаю отладчик в viewDebugError (core.es5. js: 8507) и следую callstack), но в конечном итоге исчезает и появляется ошибка выше. я уже вижу https://indepth.dev/everything-you-need-to-know-about-the-expressionchangedafterithasbeencheckederror-error/ информацию об ошибке, но она вообще не понимает.

edit

ошибка возникает при вызове метода подписки функции signUpUser () в тс, при нажатии кнопки «регистрация» в html

...