Error two clicks to be able to login Angular 16

26 Views Asked by At

When trying to log in, I need to click twice, when I click the first time it doesn't work, when I click the second time it works, I'm not sure if that's it but I'm getting an error: TypeError: Cannot read properties of undefined (reading 'name') and I don't know how to solve it, I already put a console.log() in the submitLogin() function and it says that the user does not have a defined name

Component HTML:

<div class="center-container">
  <ng-template #loadingPage>
    <div *ngIf="!firstLoad">
      <div class="flex justify-content-center">
        <mat-progress-bar style="max-width: 400px;margin:10px" mode="indeterminate" color="primary"></mat-progress-bar>
      </div>
    </div>
  </ng-template>
  <mat-card class="login-card" >
    <mat-card-header>
      <div class="mt-4 text-center">
        <img mat-card-image class="align-items-center"  ngSrc="assets/main-logo.png" width="300" height="70" >
        
      </div>
      
    </mat-card-header>
    
    <mat-card-content>
      <form class="flex flex-wrap align-items-center justify-content-center mt-2 mb-4" [formGroup]="loginForm">
        <div class="grid-form-login">
          <mat-form-field class="input-form-login">
            <mat-label>Login</mat-label>
            <input matInput formControlName="identifier">
          </mat-form-field>
          <mat-form-field class="input-form-login">
            <mat-label>Senha</mat-label>
            <input matInput type="password" formControlName="password">
          </mat-form-field>
          <div class="flex justify-content-left">
            <mat-checkbox class="example-margin" [checked]="rememberMe" [disabled]="loading" (click)="changeRememberMe()">Manter-se conectado</mat-checkbox>
          </div>
          <button mat-raised-button color="primary" style="width: 100%;" [disabled]="loading" (click)="submitLogin()">Entrar</button>&nbsp;
          <button mat-raised-button color="basic" style="width: 100%;" [disabled]="loading" (click)="loginWithGoogle()">
            Login com o google <mat-icon svgIcon="google" aria-hidden="false" ></mat-icon>
          </button>
        </div>
      </form>
      <mat-divider></mat-divider>
    </mat-card-content>
    <mat-card-footer>
      <mat-progress-bar mode="indeterminate"  *ngIf="loading"></mat-progress-bar>
    </mat-card-footer>
  </mat-card>
</div>

<p-toast></p-toast>

My component.ts:

import { Component } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { Router } from '@angular/router';
import { MessageService } from 'primeng/api';
import { AuthService } from 'src/app/services/auth/auth.service';
import { UserService } from '../../services/user/user.service';
import { DomSanitizer, Title } from '@angular/platform-browser';
import { LoadingService } from '../../services/loading/loading.service';
import { MatIconRegistry } from '@angular/material/icon';
import { AngularFireAuth } from '@angular/fire/compat/auth';
import firebase from 'firebase/compat/app';
import { Ilogin } from 'src/app/interfaces/login';

const GOOGLE_ICON =
  `
  <?xml version="1.0" encoding="UTF-8"?>
  <svg width="36px" height="36px" viewBox="0 0 36 36" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
      <!-- Generator: Sketch 43.2 (39069) - http://www.bohemiancoding.com/sketch -->
      <title>UI/icons/color/google</title>
      <desc>Created with Sketch.</desc>
      <defs/>
      <g id="Symbols" stroke="none" stroke-width="1" fill="none" fill-rule="evenodd">
          <g id="UI/icons/color/google">
              <g id="Group" transform="translate(2.000000, 2.000000)">
                  <path d="M32.4365525,16.6024012 C32.4365525,15.4515967 32.3313665,14.344128 32.1357206,13.2820585 L16.5492615,13.2820585 L16.5492615,19.5616128 L25.4557094,19.5616128 C25.0721312,21.5908257 23.9059692,23.3098098 22.1535707,24.4613022 L22.1535707,28.5341733 L27.5019274,28.5341733 C30.631561,25.7077204 32.4365525,21.5461142 32.4365525,16.6024012 L32.4365525,16.6024012 Z" id="Shape" fill="#4285F4"/>
                  <path d="M16.5492615,32.4674071 C21.0175621,32.4674071 24.7635856,31.0139403 27.5019274,28.5341733 L22.1535707,24.4613022 C20.6718508,25.4353244 18.7756982,26.0110706 16.5492615,26.0110706 C12.2387399,26.0110706 8.59088994,23.1557272 7.2893887,19.3181072 L1.76011213,19.3181072 L1.76011213,23.5244249 C4.48302664,28.8299569 10.0796222,32.4674071 16.5492615,32.4674071 L16.5492615,32.4674071 Z" id="Shape" fill="#34A853"/>
                  <path d="M7.2893887,19.3181072 C6.95840347,18.344085 6.77047118,17.3033395 6.77047118,16.2337035 C6.77047118,15.1640676 6.95840347,14.1233221 7.2893887,13.1492999 L7.2893887,8.94298219 L1.76011213,8.94298219 C0.639530783,11.1345322 0,13.6142992 0,16.2337035 C0,18.8531079 0.639530783,21.3328749 1.76011213,23.5244249 L7.2893887,19.3181072 L7.2893887,19.3181072 Z" id="Shape" fill="#FBBC05"/>
                  <path d="M16.5492615,6.4563365 C18.9790577,6.4563365 21.160615,7.27558824 22.8758478,8.88382548 L27.6225407,4.22764161 C24.755872,1.60892511 21.0098485,0 16.5492615,0 C10.0803235,0 4.48302664,3.63813805 1.76011213,8.94298219 L7.2893887,13.1492999 C8.59088994,9.31236774 12.2394411,6.4563365 16.5492615,6.4563365 Z" id="Shape" fill="#EA4335"/>
              </g>
          </g>
      </g>
  </svg>
`;
@Component({
  selector: 'app-login',
  templateUrl: './login.component.html',
  styleUrls: ['./login.component.scss']
})
export class LoginComponent {
  hidePassword: boolean = true;

  loginForm: FormGroup;

  rememberMe: boolean = false;

  firstLoad: boolean = true;

  loading: boolean = false;
  

  constructor(
    private formBuilder: FormBuilder,
    private authService: AuthService,
    private userService: UserService,
    private messageService: MessageService,
    private router: Router,
    private titleService: Title,
    public loadingService: LoadingService,
    public iconRegistry: MatIconRegistry, 
    public sanitizer: DomSanitizer,
    public auth: AngularFireAuth,
  ) {
    iconRegistry.addSvgIconLiteral('google', sanitizer.bypassSecurityTrustHtml(GOOGLE_ICON));
  }

  ngOnInit(): void {
    this.titleService.setTitle('Login');
    this.loginForm = this.formBuilder.group({
      identifier: ['', [Validators.required]],
      password: ['', [Validators.required]]
    });

    const body = document.getElementsByTagName("body")[0];
    body.classList.add("bg-default");

  }

  submitLogin() {
    // console.log("CONSOLE.LOG:", this.submitLogin());
    this.firstLoad = false;
    this.loading = true;
    this.authService.login(this.loginForm.value).subscribe({
      next: ({jwt, user}: any) => {

        if (user && user.name !== undefined) {
          console.log("Nome do usuario:", user.name);
        } else {
          console.log("usuario Nao possui um nome definido");
        }

        this.rememberMe ? localStorage.setItem('Authorization', `Bearer ${jwt}`) : sessionStorage.setItem('Authorization', `Bearer ${jwt}`);

        localStorage.setItem('schoolId', user.schoolOwner?.id);
        localStorage.setItem('roleName', user.role.name.toLowerCase());

        this.router.navigate(['affiliated-school/list'])
        // this.userService.findMe().subscribe({
        //   next: (user: any) => {
        //     localStorage.setItem('schoolId', user.schoolOwner?.id);
        //     localStorage.setItem('roleName', user.role.name.toLowerCase());
        //     // if(user.affiliatedSchools.length === 1 && user.role.name.toLowerCase() != 'owner')
        //     // localStorage.setItem('affiliatedSchoolId', user.affiliatedSchools[0].id);
        //     user.role.name === 'Owner' || user.role.name === 'Teacher' || user.role.name === 'Manager' || user.role.name === 'Secretary' ? this.router.navigate(['affiliated-school/list']) : this.router.navigate(['school-class/list']);
        //   }
        // });
      },
      error: () => {
        this.loading = false;
        this.messageService.add({ severity: 'error', summary: 'Erro', detail: 'Usuario ou senha incorreto.' });
      },
      complete: () => {
        this.loading = false;
      }
    });
  }

  changeRememberMe() {
    this.rememberMe = !this.rememberMe;
  }

  ngOnDestroy() {
    const body = document.getElementsByTagName("body")[0];
    body.classList.remove("bg-default");
  }

  async loginWithGoogle () {
    this.loading = true;

    await this.auth.signInWithPopup(new firebase.auth.GoogleAuthProvider()).catch(err => {
      console.log(err)
      this.loading = false
    })

    const token = await firebase.auth().currentUser.getIdToken()

    const payload = {
      token: token,
      provider: 'firebase'
    } as Ilogin

    this.authService.login(payload).subscribe({
      next: ({ jwt, user }: any) => {

        this.rememberMe ? localStorage.setItem('Authorization', `Bearer ${jwt}`) : sessionStorage.setItem('Authorization', `Bearer ${jwt}`);

        localStorage.setItem('schoolId', user.schoolOwner?.id);
        localStorage.setItem('roleName', user.name.toLowerCase());

        this.router.navigate(['affiliated-school/list'])
        // this.userService.findMe().subscribe({
        //   next: (user: any) => {
        //     localStorage.setItem('schoolId', user.schoolOwner?.id);
        //     localStorage.setItem('roleName', user.role.name.toLowerCase());
        //     if(user.role.name === 'Student' || user.role.name === 'Teacher' || user.role.name === 'Parent')
        //       localStorage.setItem('affiliatedSchoolId', user.affiliatedSchool.id);
        //     user.role.name === 'Owner' ? this.router.navigate(['affiliated-school/list']) : this.router.navigate(['school-class/list']);
        //   },
        //   error: (error) => {
        //     console.log(error)
        //     this.messageService.add({ severity: 'error', summary: 'Erro', detail: 'Ocorreu um erro ao logar com o google' });
        //   }
        // });
      },
      error: (error) => {
        this.loading = false;
        console.log(error)
        this.messageService.add({ severity: 'error', summary: 'Erro', detail: 'Ocorreu um erro ao logar com o google' });
      },
      complete: () => {
        this.loading = false;
      }
    })
  }

}

login.component.ts:82 
 ERROR TypeError: Cannot read properties of undefined (reading 'name')
    at Object.next (login.component.ts:94:52)
    at ConsumerObserver.next (Subscriber.js:91:33)
    at SafeSubscriber._next (Subscriber.js:60:26)
    at SafeSubscriber.next (Subscriber.js:31:18)
    at map.js:7:24
    at OperatorSubscriber._next (OperatorSubscriber.js:13:21)
    at OperatorSubscriber.next (Subscriber.js:31:18)
    at filter.js:6:128
    at OperatorSubscriber._next (OperatorSubscriber.js:13:21)
    at OperatorSubscriber.next (Subscriber.js:31:18)
Zone - XMLHttpRequest.addEventListener:load (assíncrono)        
submitLogin @   login.component.ts:82
LoginComponent_Template_button_click_21_listener    @   login.component.html:32
Zone - HTMLButtonElement.addEventListener:click (assíncrono)        
LoginComponent_Template @   login.component.html:32
Zone - Promise.then (assíncrono)        
logout  @   auth.service.ts:65
logout  @   toolbar.component.ts:45
ToolbarComponent_Template_button_click_18_listener  @   toolbar.component.html:47
Zone - HTMLButtonElement.addEventListener:click (assíncrono)        
ToolbarComponent_Template   @   toolbar.component.html:47
Promise.then (assíncrono)       
4913    @   main.ts:8
__webpack_exec__    @   main.ts:9
(anônimo)   @   main.ts:9
(anônimo)   @   main.ts:9
(anônimo)

I need to know how to set the name property to be sure if this is what causes the problem of two clicks to log in

1

There are 1 best solutions below

0
Naren Murali On

Since you have not shared the auth service code, we can simply use ?. of typescript to null check the user so that will get rid of the console error!

  submitLogin() {
    this.firstLoad = false;
    this.loading = true;
    this.authService.login(this.loginForm.value).subscribe({
      next: ({jwt, user}: any) => {

        if (user?.name !== undefined) {
          console.log("Nome do usuario:", user.name);
        } else {
          console.log("usuario Nao possui um nome definido");
        }

        this.rememberMe ? localStorage.setItem('Authorization', `Bearer ${jwt}`) : sessionStorage.setItem('Authorization', `Bearer ${jwt}`);

        localStorage.setItem('schoolId', user?.schoolOwner?.id);
        localStorage.setItem('roleName', user?.role?.name?.toLowerCase());

        this.router.navigate(['affiliated-school/list'])
        // this.userService.findMe().subscribe({
        //   next: (user: any) => {
        //     localStorage.setItem('schoolId', user.schoolOwner?.id);
        //     localStorage.setItem('roleName', user.role.name.toLowerCase());
        //     // if(user.affiliatedSchools.length === 1 && user.role.name.toLowerCase() != 'owner')
        //     // localStorage.setItem('affiliatedSchoolId', user.affiliatedSchools[0].id);
        //     user.role.name === 'Owner' || user.role.name === 'Teacher' || user.role.name === 'Manager' || user.role.name === 'Secretary' ? this.router.navigate(['affiliated-school/list']) : this.router.navigate(['school-class/list']);
        //   }
        // });
      },
      error: () => {
        this.loading = false;
        this.messageService.add({ severity: 'error', summary: 'Erro', detail: 'Usuario ou senha incorreto.' });
      },
      complete: () => {
        this.loading = false;
      }
    });
  }