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

Trouble passing data back to main window after clicking ng-modal button in Angular

While working on the NG-Model window, I encountered an issue with my code. Initially, everything was functioning as expected when applied to a select element that is a radio button. However, when I changed the code to use the Click method for a button, it ...

Trouble occurs in the HTML code when trying to access a property from an inherited interface in Angular

Currently, I am working with Angular 17 and have encountered a specific query: In my project, there is an IDetails interface containing certain properties: export interface IDetails { summary: Summary; description: string; } Additionally, there is an ...

The Value Entered in Angular is Unsaved

I have encountered an issue with my app's table functionality. The user can enter information into an input field and save it, but upon refreshing the page, the field appears empty as if no data was entered. Can someone please review my code snippet b ...

How to convert typescript path aliases into relative paths for NPM deployment?

I am currently working on a typescript project that utilizes paths for imports. For instance: "paths": { "@example/*": ["./src/*"], } This allows the project to import files directly using statements like: import { foo } from "@example/boo/foo"; Whe ...

Angular 6 implement a waiting function using the subscribe method

I need to make multiple calls to a service using forEach, where each call depends on the completion of the previous one. The code is as follows: itemDefaultConfiguration.command = (onclick) => { this.createConfiguration(configuration.components); ...

Error: Uncaught TypeError - The function boss.SetBelongToClan is not defined

Currently, I am faced with an issue while working on a typescript and sequelize project within an express application. The problem arises when trying to create a type-safe interface for utilizing the associate function. Within my Instance interface, there ...

Issue with dynamic HTML preventing Bootstrap tooltip functionality

There's an HTML page where a section is dynamically generated through HTML injection from a typescript angularjs controller using $sce and ng-bind-html. The issue is that the custom bootstrap tooltip style doesn't seem to be applied, and only t ...

understanding the life cycle of components in Ionic

I created a component with the following structure: export class AcknowledgementComponent implements AfterViewInit { private description: string; @Input('period') period: string; constructor() { } ngAfterViewInit() { console.log ...

Using AngularJS and Express to send intricate form data to a RESTful API

I need some help with structuring nested data for a POST request to an API. The API I built is for a survey-making application and it follows a User --> Quiz --> Question --> QuestionChoice structure, where each arrow represents a one-to-many relationship. ...

Objects vanish 10 seconds after appearing [Angular2, *ngFor]

My Angular2 template is quite straightforward: <span *ngFor="let item of items"> {{ item.description }} </span> Here is the TypeScript logic for it: let list = new Map(); for(let j = 0; j < 100; j++) { list.set(j, { description: j.toS ...

Error in AngularJS: Loading null value for an option tag

I have successfully bound all the values to the option tags using Angular JS. However, I am facing an issue where a null value is getting appended on load. Additionally, when I set a value in my JavaScript code, it only sets the first value and does not ch ...

Building a resolver to modify a DynamoDB item via AppSync using the AWS Cloud Development Kit (CDK)

After successfully creating a resolver to add an item in the table using the code provided below, I am now seeking assistance for replicating the same functionality for an update operation. const configSettingsDS = api.addDynamoDbDataSource('configSet ...

What is the method for storing a JSON object path in a variable for use in a template?

Trying to fetch data from a lengthy path has proven challenging for me. I attempted to store the path in a variable and incorporate it into the template, but encountered some issues. Could someone assist me with this? Here is what I have tried: My store ...

Leveraging AngularJS for a Windows store app

After attempting to integrate AngularJS into my Windows store application, I came across a few recommended solutions: Unfortunately, these solutions did not work as expected. While I didn't encounter the Unable to add dynamic content error, AngularJS ...

Utilizing sorting and filtering functionalities on an Angular data table

Recently, I decided to enhance my Angular skills by downloading a demo app. While working on the basics of Angular, I encountered a problem with applying a filter and sort to a data table in the app. Despite referring to some examples, I am uncertain about ...

centering an angular material card on the webpage

Currently, I have developed a Registration script that enables users to Sign Up on my website. However, the issue I am facing is that the angular material card, which houses the sign up interface, is not centered. Despite trying various methods such as & ...

Why is it necessary to include a dollar sign before interpolation in Angular?

While diving into a tutorial, I stumbled upon a piece of code that piqued my curiosity. I grasped the concept that appending a dollar sign as a suffix indicates observability, but I wonder why the dollar sign was also prefixed to this.log(`updated hero i ...

Using the "this" keyword is required for an Angular Service-created function

Although this question leans more towards JavaScript than Angular, I encountered an issue while creating a service. The function call looked like this: // controller injects activityApi , then service function call is made var activities = activityApi.get ...

Simultaneously iterate through two recursive arrays (each containing another array) using JavaScript

I have two sets of arrays composed of objects, each of which may contain another set of arrays. How can I efficiently iterate through both arrays and compare them? interface items { name:string; subItems:items[]; value:string; } Array A=['parent1&ap ...

Exploring the hidden gems of npm package.json: the keys

There are some keys in the package.json file of Angular 2/4's source code that remain undocumented: { "name": "@angular/platform-browser/animations", "typings": "../animations.d.ts", "main": "../bundles/platform-browser-animations.umd.js", "m ...