Please click twice in order to log in to Angular 16

Whenever I attempt to log in, I face the issue of having to click twice. The first click does not work, but the second one does. Additionally, an error message pops up: TypeError: Cannot read properties of undefined (reading 'name'). I am unsure how to resolve this issue. After adding a console.log() in the submitLogin() function, it indicates that the user's name is not defined.

Here is my 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>

Check out my component.ts code snippet below:

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';

// Google Icon SVG Content
const GOOGLE_ICON = `
  <?xml version="1.0" encoding="UTF-8"?>
  <!-- Include your SVG content here -->
`;

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

I would appreciate guidance on resolving the issue related to having to double-click for logging in and setting the 'name' property correctly.

Answer №1

If the auth service code is not shared, we can utilize ?. in typescript for null checking the user and eliminating 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("User's name:", user.name);
        } else {
          console.log("User does not have a defined name");
        }

        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'])
      
      },
      error: () => {
        this.loading = false;
        this.messageService.add({ severity: 'error', summary: 'Error', detail: 'Incorrect username or password.' });
      },
      complete: () => {
        this.loading = false;
      }
    });
  }

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Does the React memo function modify the component's prop type?

I've come across a strange issue where defining two components causes compilation errors when written separately but not when written in the same file. test3.tsx import React from "react"; type ValueType = number[] | string[] | number | st ...

Issue with Angular 8 docker container: module not found despite being installed

I am currently working on an Angular 8 single-page application (SPA). Utilizing a Dockerfile that is managed and executed through a Docker Compose setup. Everything was functioning smoothly for weeks until today when, out of nowhere, the setup stopped wor ...

A more efficient way to specify children types in Typescript React is by directly specifying the type in the function instead

What is the reason behind this: interface UserSidebarProps { children? : React.ReactNode } function UserSidebar({children}: UserSidebarProps) { return ( <div> {children} </div> ) } Why doesn't this work? function User ...

Leverage the power of Angular 2 components within your Asp.net MVC

I am currently working on an Asp Mvc project which utilizes Angular 1.4 for the frontend. While my project is not designed to be a single page application, I am interested in incorporating Angular 2 without transitioning the entire project into a SPA. Aft ...

Get the socket identification from ngx-socket-io

After incorporating ngx-socket-io into my project, I encountered a hurdle while attempting to obtain the socket id. Is there anyone who has knowledge on how this can be accomplished? (I am utilizing service initialization instead of the one in the app Mo ...

Once the table is created in TypeORM, make sure to insert essential master data such as types and statuses

Hey there, I have a question regarding NestJS and typeORM. My issue is with inserting default values into tables after creating them. For example, I have a priority table where I need to insert High/Medium/Low values. Despite trying everything in the typeo ...

Tips for setting up PhantomJS with Karma test runner

I've been attempting to run the karmatest runner with phantomJS on my Windows 7 machine. Here's the configuration file I'm using: // Karma configuration // http://karma-runner.github.io/0.12/config/configuration-file.html // Generated on 20 ...

Error: Unable to Locate Module (Typescript with baseUrl Configuration)

Struggling to implement custom paths in my TypeScript project, I keep encountering the "webpackMissingModule" error due to webpack not recognizing my modules. I've attempted various solutions without any success. Any suggestions or ideas? Some packa ...

AngularJS: The 'myInputName' property is not defined and cannot be read

Encountering an error with AngularJS: https://i.sstatic.net/TBHem.png The issue is related to the titleInput TextBox name property: @Html.TextBox("titleInput", null, new { @placeholder = @T("Message title"), @class = "form-control", ng_model = "feed.fee ...

Tips for Verifying a User's Identity using Username and Password

After examining this Angular 2 solution: state: string = ''; error: any; constructor(public af: AngularFire, private router: Router) { this.af.auth.subscribe(auth => { if (auth) { this.router.navigateByUrl('/mem ...

Router-outlet @input decorator experiencing issues with multiple components

Within my router module, I have a route set up for /dashboard. This route includes multiple components: a parent component and several child components. The data I am trying to pass (an array of objects called tablesPanorama) is being sent from the parent ...

Importing BrowserAnimationsModule in the core module may lead to dysfunctional behavior

When restructuring a larger app, I divided it into modules such as feature modules, core module, and shared module. Utilizing Angular Material required me to import BrowserAnimationsModule, which I initially placed in the Shared Module. Everything function ...

The title tag's ng-bind should be placed outside of the element

When using ng-bind for the title tag inside the header, it seems to produce unexpected behavior. Here is an example of the code: <title page-title ng-bind="page_title"></title> and this is the resulting output: My Page Sucks <titl ...

Is it possible to showcase content when double curly brackets are nested within another set of double curly brackets

Having this specific case, I am interested in showcasing information from the model. Is it possible to utilize double curly braces within another set of double curly braces? ...

Utilize SWR in NextJS to efficiently manage API redirection duplication

When using SWR to fetch data, I encountered an error where the default path of nextjs was repeated: http://localhost:3000/127.0.0.1:8000/api/posts/get-five-post-popular?skip=0&limit=5 Here is my tsx code: 'use client' import useSWR from &quo ...

How to retrieve the innerWidth value using AngularJS

I am seeking a way to access the innerWidth of my browser within my controller. Although I have come across a directive that can display the width on the screen, I would prefer to have this functionality within my controller. The ng-repeat in my code relie ...

Adding a Select Box and its options dynamically to the DOM with AngularJS: A complete guide

After dynamically adding a Select Box with empty options to the DOM, what is the best way to populate it with options (ng-options)? I am facing a situation where users can add multiple select boxes to the DOM during runtime and then input values into these ...

Alert me in TypeScript whenever a method reference is detected

When passing a function reference as a parameter to another function and then calling it elsewhere, the context of "this" gets lost. To avoid this issue, I have to convert the method into an arrow function. Here's an example to illustrate: class Mees ...

Incorporate a directive dynamically within a separate directive

Introducing the table-div directive, which is responsible for rendering both the header and body of a table. Each row within tbody has the option to incorporate additional functionality through a custom directive that can display data linked to its parent ...

Exploring the means to obtain the element where another element is dropped in ngDraggable within AngularJS

We are currently utilizing ngDraggable in AngularJS. Our goal is to retrieve the element on which another element is dropped. While we can obtain data of the drag element using ng-drag-data, we are facing difficulties in capturing data of the drop locati ...