How to login validation in Angular?

Asked

Viewed 1,133 times

-1

I would like to know how to do it in case the user enters a user login and invalid password appears the message "Invalid login". Follow the code I’ve already made.

import { Component, OnInit } from '@angular/core';
import { AuthService } from './auth.service';
import { Usuario } from './usuario';
import { User } from "./user";

@Component({
  selector: 'ngx-login',
  templateUrl: './login.component.html',
  styleUrls: ['./login.scss'],
})
export class LoginComponent implements OnInit {

  _user: User = new User();
  constructor(private _authService: AuthService) { }

  ngOnInit() {
    this.logout();
  }

  logout() {
    this._authService.userNoAuthenticated();
    if (this._authService.userIsAuthenticated() === true) {
      location.reload();
    }
  }

  makeLogin() {
    this._authService.getUser(this._user);
  }
}
<nb-auth-block>
    <h2 class="title">Login</h2>
    <small class="form-text sub-title">Olá! Faça login com seu email</small>

    <div class="row">
        <div class="input-field col s12">
            <div class="form-group">
                <label for="input-email" class="sr-only">Digite seu email</label>
                <input [(ngModel)]="_user.email" id="usuario" class="form-control" placeholder="Digite seu email">
            </div>
            <div class="form-group">
                <label for="input-password" class="sr-only">Password</label>
                <input [(ngModel)]="_user.password" id="senha" type="password" class="form-control" placeholder="Senha">
            </div>
            <button type="submit" name="action" (click)="makeLogin()" class="btn btn-block btn-hero-success"> Entrar </button>
        </div>
    </div>

    <br>
  <div *ngIf="!customerId"> Login ou senha invalida </div>

 
</nb-auth-block>

import { Router } from '@angular/router';
import { Component, Injectable, EventEmitter } from '@angular/core';
import { User } from './user';
import { Usuario } from './usuario';
import { Http, Response } from '@angular/http';
import { md5 } from './md5';
import { Observable } from 'rxjs/Observable';

import 'rxjs/Rx';

@Injectable()
export class AuthService {
  // customerId: any;

  constructor(private router: Router, private http: Http) { }

  private userAuthenticated: boolean = false;
  private customerId: string = '';
  private linkPortal: string;
  public user: User[] = [];
  private userString: string;
  private errorMessage: any = '';
  private url: string = 'http://14.28.240.19:2088/api/values/GetUser/';
  private hash: string;
  private userName: string;

  makeLogin() {
    // this.userString = users.email + users.password;

    if (this.userIsAuthenticated() === true) {
      this.userAuthenticated = false;
      console.log('Login verdadeiro');
    } else {
      const e = md5(this.userString);

      this.http
        .get(this.url + e)
        .map((res) => res.json())
        .subscribe((data) => this.user = data,
        () => console.log(this.user));
      for (const key in this.user) {
        if (this.user.hasOwnProperty(key)) {
          const element = this.user[key];
          this.customerId = element['IdCustomer'];
          this.linkPortal = element['linkPortal'];
          this.userName = element['UserName'];
          if (element['UserName'] !== '') {
            this.userAuthenticated = true;
            this.router.navigate(['/pages/dashboard']);
          } else {
            this.userAuthenticated = false;
          }
        }
      }
      if (this.customerId === '') {
        this.data();
      console.log('Login false');
      }
    }

  }

  data() {
    const dayAsync = new Promise((resolve, reject) => {
      setTimeout(() => {
        this.makeLogin();
      }, 1000);
    });
  }

  getUser(users: User) {
    this.userString = users.email + users.password;
    this.makeLogin();
  }

  public customerIsId() {
    return this.customerId;
  }

  public customerIsUserName() {
    return this.userName;
  }

  public customerIsLinkPortal() {
    return this.linkPortal;
  }

  userIsAuthenticated() {
    return this.userAuthenticated;
  }

  userNoAuthenticated() {
    this.customerId = '';
    this.userString = '';
    this.user = null;
  }

}

  makeLogin() {
this._authService.getUser(this._user)
  if ( this._authService.userIsAuthenticated() === false ){
      this.userAuthenticated = true;
      console.log('Login valido');
      this.messageLoginValido = 'Login valido';
    }else{
    this.message = 'Login invalido';
  }

}

<nb-auth-block>
<h2 class="title">Login</h2>
<small class="form-text sub-title">Olá! Faça login com seu email</small>

<div class="row">
    <div class="input-field col s12">
        <div class="form-group">
            <label for="input-email" class="sr-only">Digite seu email</label>
            <input [(ngModel)]="_user.email" id="usuario" class="form-control" placeholder="Digite seu email">
        </div>
        <div class="form-group">
            <label for="input-password" class="sr-only">Password</label>
            <input [(ngModel)]="_user.password" id="senha" type="password" class="form-control" placeholder="Senha">
        </div>
        <button type="submit" name="action" (click)="makeLogin()" class="btn btn-block btn-hero-success"> Entrar </button>
    </div>
</div>

<br>

{{message}} {{messageLoginValid}}

2 answers

0

In his makeLogin() use the subscribe:

    ....
    this._authService.getUser(this._user )
      .subscribe(
        res => {
          if( [ CONDICAO AQUI DO RETORNO DO res] ){
            this.userAuthenticated = true;
            this.router.navigate(['/pages/dashboard']);
          } 
        },
        err => {
          this.message = 'Login invalido';
        }
    );
    ...
  • Hello, I would like to know how to use . subscribe in my project, because I am new in angular in I have no idea how to use.

  • See this: http://kazale.com/curso-angular-2-aula-10-acesso-http-um-servor-remote/ No item: from 3. Criando um serviço utilitário para acesso HTTP

  • You can do!!!

  • I made it as a request but you’re making a mistake:

  • ERROR in src/app/pages/login/login.component.ts(33,5): error TS1128: Declaration or statement expected. src/app/pages/login/login.component.ts(46,1): error TS1005: '}' expected.

  • Forgot to close the { with } in the archive login.component.ts line 46

  • makeLogin() {&#xA; this._authService.getUser(this._user)&#xA; if ( this._authService.userIsAuthenticated() === false ){&#xA; this.userAuthenticated = true;&#xA; console.log('Login valido');&#xA; this.messageLoginValido = 'Login valido';&#xA; }else{&#xA; this.message = 'Login invalido';&#xA; }&#xA;&#xA; }

  • This is my logic.

  • This is my Component.html:

  • <button type="Submit" name="action" (click)="makeLogin()" class="btn btn-block btn-Hero-Success"> Login </button> </div> </div> <br> <div *ngIf="message"> {message}} </div> <div *ngIf="messageLoginValido"> {{geLoginValido}} </div>

Show 5 more comments

0

Try to map the answer.

    this._authService.getUser(this._user)
     .map( res => res.json()) //map
     .subscribe(
      res => {
        if( this._authService.userIsAuthenticated() === false ){
          this.userAuthenticated = true;
          this.router.navigate(['/pages/dashboard']);
        }
        // Tratativa de login incorreto aqui 
        //!customerId ~ usa esse cara atribuindo para undefinded para dar a mensagem de login inválido
      },
      err => {
        this.message = 'Login invalido';
      }
  );

Browser other questions tagged

You are not signed in. Login or sign up in order to post.