Problems with user existence in node.js / angular

0

Good day community, I have a question, I have an edit form, but in the backend I have a method that if the email already exists, I can not edit the form, the problem is that in angular the input appears filled with the data, and if I change everything except the email, it does not leave me because it sends me the input email information, as it would do to send me the email input information only if I write about it, I have tried with dirty but it gives me undefined because I think the information from the backend already comes like this, I think the problem has been from node.js. I leave the node.js email validation code.

  function updateUser(req, res) {
  var userId = req.params.id;
  var params = req.body;
  var user = new User();
  user.email = params.email;
  if (userId != req.user.sub) {
    return res.send({ message: 'No tienes permisos' });
  }
  User.find({ email: params.email.toLowerCase() }, (err, docs) => {
    if (!docs.length) {
      User.findByIdAndUpdate(userId, params, (err, userUpdated) => {
        if (err) {
          res.status(500).send({ message: 'Error updating the user' 
});
        } else {
          if (!userUpdated) {
            res.status(404).send({ message: "The user can't be update" });
          } else {
            res.status(200).send({ user: userUpdated });
          }
        }
      });
     } else {
       res.json({ msg: 'El email ya ha sido elegido por otra persona' 
 });
}
  });
}

Here is the angular update.ts

    import { Component, OnInit } from '@angular/core';
    import { User } from '../../user';
    import { AuthService } from '../../auth.service';
    import { GLOBAL } from '../../../global';
    import { ActivatedRoute, Router, Params } from '@angular/router';
    import { FormBuilder, FormGroup, Validators } from '@angular/forms';

    @Component({
      selector: 'app-update-user',
      templateUrl: './update-user.component.html',
      styleUrls: ['./update-user.component.scss']
    })
    export class UpdateUserComponent implements OnInit {
      public rForm: FormGroup;
      public user: User;
      public identity;
      public token;
      public url: string;
      public alertMessage: string;
      public filesToUpload: Array<File>;

      constructor(
        private authService: AuthService,
        private route: ActivatedRoute,
        private router: Router,
        private fb: FormBuilder
      ) {
        this.url = GLOBAL.url;

        this.rForm = fb.group({
          update: fb.group({
            name: [null, Validators.compose([Validators.required])],
            lastname: [null, Validators.compose([Validators.required])]
            email: [null, Validators.compose([Validators.email])]
          })
        });
      }

      ngOnInit() {
        this.identity = this.authService.getIdentity();
        this.token = this.authService.getToken();
        this.user = this.identity;
      }

      fileChangeEvent(fileInput: any) {
        this.filesToUpload = <Array<File>>fileInput.target.files;
      }

      onSubmit() {
        this.authService.updateUser(this.user).subscribe(
          response => {
            if (!response.user) {
              console.log(response.user);
              this.alertMessage = 'El usuario no se ha actualizado';
            } else {
              console.log('desde el this.user' + this.user.name);
              console.log('desde el response.user' + response.user.name);
              localStorage.setItem('identity', JSON.stringify(this.user));

              let identity = this.user;
              this.identity = identity;
              this.authService.sendIden(this.identity);
              if (!this.filesToUpload) {
              } else {
                this.makeFileRequest(
                  this.url + 'imagen-usuario/' + this.user._id,
                  [],
                  this.filesToUpload
                ).then((result: any) => {
                  this.user.image = result.image;
                  localStorage.setItem('identity', JSON.stringify(this.user));
                  let image_path = this.url + 'ver-imagen/' + this.user.image;
                });
              }
              this.alertMessage = 'El usuario se ha actualizado';
              this.authService.sendIden(this.identity);
            }
          },
          error => {
            var alertMessage = <any>error;
            if (alertMessage != null) {
              var body = JSON.parse(error._body);
              this.alertMessage = body.message;
            }
          }
        );
      }

And here is the Update.html

<div *ngIf="identity">
      {{alertMessage}}
      <form [formGroup]="rForm" (ngSubmit)="onSubmit()">
        <div formGroupName="update">
          <label>Nombre</label>
          <input type="text" formControlName="name" [(ngModel)]="user.name">
          <label>Apellido</label>
          <input type="text" formControlName="lastname" [(ngModel)]="user.lastname">
          <label>Email</label>
          <input type="email" formControlName="email" [(ngModel)]="user.email">
          <div class="image_for_edit">
            <img src= '{{url+"ver-imagen/"+user.image}}' style="width: 50px;" alt="">
            <p>

              <label >Upload your avatar</label>
              <input type="file" placegolder="Upload image..."(change)="fileChangeEvent($event)">
            </p>
          </div>
        </div>

          <input type="submit"  value="Actualizar informacion" [disabled]="rForm.invalid">   
      </form>
    </div>  
    
asked by Vjotaa 22.06.2017 в 16:02
source

0 answers