The system encountered an issue while trying to access the property 'emailVerified' of an undefined object

I am currently working on retrieving the current user and attempting to assign the user values to a getter. In the constructor, I can see in the console that it is returning "email verified" as true. However, when trying to set it in the getter, I am encountering an error message that reads "Cannot read property 'emailVerified' of undefined." Below is the code snippet for reference:

import { Injectable } from "@angular/core";
import { AngularFireAuth } from "@angular/fire/auth";
import * as firebase from "firebase/app";
//import 'rxjs/add/operator/toPromise';

@Injectable({
  providedIn: "root"
})
export class AuthService {

  userData: any; // Store information of logged-in user

  constructor(public afAuth: AngularFireAuth) {

    /* Check if user is logged in and initialize to null when logged out */
    this.afAuth.authState.subscribe(user => {
      if (user) {
        this.userData = user;
        console.log(this.userData, this.userData.emailVerified)

      } else {
        this.userData = null;
      }
    })
  }

  // Returns true if user is logged in and email is verified
  get isLoggedIn(): boolean {
    const user = this.userData;
    return ( user !== null && user.emailVerified !== false ) ? true : false;
  }
}

Answer ā„–1

This function checks if the user is logged in and has a verified email:


  get isLoggedIn(): boolean {
    const currentUser = this.userData;
    if(currentUser === null || currentUser === undefined) return false;
    return currentUser.emailVerified;
  }

Answer ā„–2

Arrow functions differ from regular functions in that they do not have their own this, causing an issue when trying to access the emailVerified key and resulting in an error such as

Cannot read property 'emailVerified' of undefined

Take a look at this revised code snippet:

/* Check if user is logged in or out */
    this.afAuth.authState.subscribe( (user) => {
      if (user) {
        this.userData = user;
        console.log(this.userData, this.userData.emailVerified);

      } else {
        this.userData = null;
      }
    })

Give this updated version a try!

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

Utilize Lodash to iterate through functions in a loop and retrieve the first matching result

I am looking to iterate through an array of objects and call a method on them. If the result of that method meets certain conditions, I want to immediately return that result. The current implementation is as follows: public getFirstMatch(value: string, a ...

Steps for linking HTTP requests in Angular 2 depending on the type of response

My attempt to create an api call from a remote server and then, if an error occurs, make another request from my local server is not working as expected. I am encountering errors and need help to determine if my approach is feasible. Here is the code snip ...

Angular2: Once user is authenticated, navigate to specific routes

I've developed an admin panel with a router for page navigation. The layout of the admin panel includes a sidebar (Component), header (Component), and content (Component). Within the content, I have inserted <router-outlet></router-outlet> ...

It is not possible to import Angular MockBackend with a production build

In my Angular application, I have set up a mock backend for use in end-to-end tests. To determine whether to use the mock backend or an actual HTTP backend service, I created a factory function. The factory function checks if the build is for production a ...

Perplexed by the implementation of "require(...)" in TypeScript

After reading several blog posts, my understanding of TypeScript modules remains confusing. I have worked with three different modules (all installed via npm) and encountered varying behavior: (1) Importing and using Angular 2 from npm required me to add ...

I am searching for answers to solve issues related to a JSON file

I am currently working on a tool that searches for matches in an input field by comparing the keywords entered by the user with a JSON. During my testing phase, I focused on using a single API that provides information about different countries and fortun ...

Tips for ensuring users stay logged in even after refreshing the page using Firebase's persistence feature

I implemented the use of Context API to manage user login state and also utilized Firebase Auth persistence to keep users logged in even after a page reload, however, it seems to not be working as expected. While the user information is being saved in the ...

Guidelines for Nestjs class-validator exception - implementing metadata information for @IsNotIn validator error handling

I have a NestJs data transfer object (dto) structured like this import { IsEmail, IsNotEmpty, IsNotIn } from 'class-validator'; import { AppService } from './app.service'; const restrictedNames = ['Name Inc', 'Acme Inc&ap ...

Create a tuple type that encompasses all possible paths within a recursive object configuration

Consider the following templates for 'business' types, representing compound and atomic states: interface CompoundState<TName extends string, TChildren extends { [key: string]: AnyCompoundState | AnyAtomicState }> { type: 'parent&ap ...

Looking to execute a service method within an authguard service?

I am a beginner with Angular and I am looking to invoke a service method within the authguard service. The specific service function that I need is as follows. Please note that I do not want to make any changes to this service function. loadOrganizations() ...

Guide to triggering an Observable depending on the result of a different Observable and obtaining an Observable as output

Looking to implement a service method in Angular 10 that returns an Observable for a custom User object. The goal is to have a service method that checks if the main service is running, and if not, return data from a local resource as an alternative. Pseu ...

leveraging Angular 2 in combination with an express-node js API

Hello, Iā€™m currently trying to wrap my head around the installation of Angular JS v2. After going through numerous tutorials, I find myself feeling quite confused. Some tutorials mention using webpack to set up a server for the application, while other ...

Sequelize v5 & Typescript Model Loader

Having previous experience with Sequelize for projects (v4), I am now venturing into starting a new project using Sequelize v5 & Typescript. I have been following Sequelize's documentation on how to define Models at: https://sequelize.org/master/ ...

A step-by-step guide on uploading images to Firebase using Ionic 4

I'm having trouble uploading images to Firebase. Can anyone offer assistance? Does anyone know how to upload images to Firebase in Ionic 4.0? The code below used to work in Ionic 2, but now there's a delay of about 30 seconds after clicking the ...

Display the ion-button if the *ngIf condition is not present

I am working with an array of cards that contain download buttons. My goal is to hide the download button in the first div if I have already downloaded and stored the data in the database, and then display the second div. <ion-card *ngFor="let data o ...

Struggling to bring in components in ReactJS

My journey with ReactJS has just begun, and I've encountered some issues with the code that I believe should work but doesn't. To start off, I set up a new ReactJS project using the npm command create-react-app. Following this, I installed Googl ...

Generate a pre-signed URL for an AWS S3 bucket object using Typescript in NextJS, allowing for easy file downloads on the client-side using @aws-sdk/S3Client

In the utilization of v3 of the S3Client, it appears that all existing examples are based on the old aws-sdk package. The goal is for the client (browser) to access a file from S3 without revealing the key from the backend. From my research, it seems tha ...

Mastering the Art of Flex Layout Grids

Here is a preview of how my grid is currently formatted: https://i.stack.imgur.com/SBChV.png The current code looks like this: <div fxLayout="row wrap"> <img class="component-logo" fxFlex="1 1 c ...

Encountering a Windows 11 issue: npm ERR! errno -4058 with ENOENT bash code

Encountered a troublesome NPM issue suddenly, after taking a brief break from working on my project. Facing the following error with core-js. npm ERR! code ENOENT npm ERR! syscall spawn bash npm ERR! path C:\Users\User1\Documents\projec ...

What kind of null/undefined is being assumed?

system details: Visual Studio Code Version: 1.47.3 Typescript Version: 4.0.0-dev.20200727 tsconfig.js: "strict": true, code example: let x = null; // x is any type let y = x; // x is null type(why? x is any type on top), y is null type x = 1; / ...