When initialized within an object, Angular may identify a field as undefined

Whenever I attempt to access a property of the object named "User," it shows up as undefined. However, upon logging the complete object to the console, the field appears with the necessary data.

Here is the console log output:


perfil.component.ts:42 undefined
perfil.component.ts:48 
{recordNumber: '00001A', name: 'Victor Manuel Arenas', dni: '75499109E', birthDate: '2000-12-04', phoneNumber: '678678678', …}
address
: 
"C\\Lorca 31"
birthDate
: 
"2000-12-04"
dni
: 
"75499109E"
email
: 
"<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="8dfbe4eef9e2ffe0ece3f8e8e1a3ecffe8e3ecfecdf8e3e4fba3eee2e0">[email protected]</a>"
name
: 
"Victor Manuel Arenas"
parking
: 
null
password
: 
"$2a$10$auBcwSsgKBWMTUUFToVb1OklqDP4O0LvW9F7vqWjnVZAGFzOVtfg6"
phoneNumber
: 
"678678678"
profilepic
: 
"profilepic_00001A.jpg"
recordNumber
: 
"00001A"
role
: 
"ALUMNO"

Method:

checking(){
    if(this.sesion.user != null){
      console.log(this.sesion.user.phonenumber);
      if(this.sesion.user.phonenumber === undefined) {
        alert("myProperty value is the special value `undefined`");
      }
    }
    
    console.log(this.sesion.user);
  }

User Interface:

import { Parking } from "./Parking";

export interface User {
    recordNumber: string;
    name: string;
    dni: string;
    birthdate: Date;
    phonenumber: string|null;
    email: string;
    address: string;
    profilepic: string|null;
    role: string;
    password: string;
    parking: Parking;
}

I have attempted various methods and pages to access this field but face no backend issues as the data reaches the front-end successfully. The problem does not lie in the object itself since the field contains the necessary data.

Answer №1

You made a mistake with the spelling of phonenumber as opposed to phoneNumber. Within your interface and checking method, you are referencing phonenumber. However, the log shows that the property should actually be typed as phoneNumber (noting the capital letter N).

const a = {foo: 'bar'};
console.log(a.foo) // => 'bar'
console.log(a.FOO) // => undefined

Remember, property access is case sensitive.

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

Tips on ensuring dispatch is finished before accessing store data. Ngrx dilemma

Is there a way to ensure that a dispatch is completed before selecting from a store? I haven't had any luck finding a solution online. How can I make sure the dispatch finishes before selecting from the store? I would appreciate any help with my code ...

Instructions on resolving the issue: The type 'string | ChatCompletionContentPart[] | null' cannot be assigned to type 'ReactNode'

I've been working on my first Saas App, similar to a ChatGPT, using NextJs with the OpenAI Api. Most of the development was based on a YouTube tutorial until I encountered two errors caused by an update in the OpenAI version. Despite trying various so ...

Error: The specified path in the MEAN stack must be either a string or Buffer

I am currently utilizing Angular 5 on the front-end, Node for back-end operations, and MongoDB as the database. My current challenge involves attempting to save an image to the database, but I keep encountering an error. Determining whether the issue lies ...

Ensure the object is not null with this Object type guard

Is there a way to create a type guard for an object directly in TypeScript? I've written a function to check any input: export function isObject(input: any) :input is Record<string,any> { return (input !== null) && (typeof input == ...

What is a way to execute a series of requests using rxjs similar to forkJoin and combineLatest, without needing to wait for all requests to finish before viewing the results?

Consider you have a list of web addresses: urls: string[] You create a set of requests (in this instance, utilizing Angular's HTTPClient.get which gives back an Observable) const requests = urls.map((url, index) => this.http.get<Film>(url) ...

I'm attempting to showcase the keyName and pattern for the arrays of Objects in Keyless and Keypresent in AngularJS, but unfortunately, I'm facing some issues

let information = { headerFields: { noKey: [{ key1: { name: "test1" }, key2: { name: "test2" }, key3: { name: "test3" } }], hasKey: [{ key1: { name: "test4" } ...

I am eager to learn how to integrate the "fs" module from Node.js into an Electron project powered by Angular

As I venture into writing my first desktop app using Electron and Angular5, I have encountered a roadblock while working with the fs module. Despite importing fs correctly (without errors in Visual Studio Code and with code completion), I faced an issue wh ...

Maven test encountering an invalid application context

When I run 'mvn test', I encounter the following error message: java.lang.IllegalStateException: Failed to load ApplicationContext ... Caused by: org.springframework.beans.factory.xml.XmlBeanDefinitionStoreException: An issue with Line 14 in ...

I am interested in utilizing the request-reply pattern with KafkaJS in a TypeScript environment. Could you provide guidance on how to successfully implement this?

I am new to Kafka and I am trying to implement the request-reply pattern using kafkajs in TypeScript. However, my current implementation is very basic and the consumers inside producers are taking too long to start, causing delays. Is there a better way to ...

Checking if the Cursor is Currently Positioned on a Chart Element in Word Addin/OfficeJS

I am looking for a way to determine if the document cursor is currently positioned inside of a Chart element using the Microsoft Word API. My current application can successfully insert text, but when I attempt to insert text into the Chart title, it ends ...

Error: Unable to retrieve options using this.getOptions function. This issue is unrelated to Vue, it is occurring within

Required Modules "dependencies": { "express": "^4.17.1", "express-static-gzip": "^2.1.1", "react": "^17.0.2", "react-dom": "^17.0.2", "reac ...

Resolving the name error: Importing definition files from node_modules/@types in Angular

After acquiring this set of definitions from a node_modules/@types file, I encountered an issue trying to import it into my js file. I went ahead and executed npm install @types/p5 before including it in my tsconfig.json as follows: "types": [ "n ...

Exploring the power of chaining multiple subscriptions in RxJs 6

I have a project using Angular 6, and I'm currently in the process of upgrading rxjs to version 6. In the previous iteration of my app, there was a specific flow where I needed to make sequential calls to observables: 1. Call an observable 2. Perfor ...

Ways to simulate a dependent class in TypeScript & JEST without modifying constructor parameters to optional

Currently, I am attempting to replicate a well-known process in Java development using TypeScript and JEST for practice. In this scenario, there is a Controller class that relies on a Service class. The connection between the two is established through the ...

Issues with Angular 6 HTTPInterceptor interface in production environments

Currently, I am utilizing the HttpInterceptor interface to include an authorization header in HTTP requests. @Injectable() export class AuthInterceptor implements HttpInterceptor { constructor( private localStorage: LocalStorageService, ...

What steps do I need to take to implement Dispatch in a React Native project?

Context App.tsx import React, { createContext, useContext, useReducer, useEffect, ReactNode, Dispatch, } from "react"; import AsyncStorage from "@react-native-async-storage/async-storage"; import { StateType, ActionType } f ...

Modeling a potentially empty array in Typescript can be achieved by implementing specific interface definitions

Here is the current situation: type A = { b: string, c: number } I have an object that I will receive from an API, which could be either A[] or [] As of now, when I attempt to use it, const apiData: A[] || [] const b = apiData[0].a // I expected this to ...

Fast + Vue3 + VueRouter Lazy Load Routes According to Files

I am currently working on implementing Domain-Driven Design (DDD) to Vue, and the project structure looks like this: src - App - ... - router - index.ts - Dashboard - ... - router - index.ts - ... The goal is for src/App/router/index.ts to ...

Numerous unspecified generic arguments

Imagine a collection of functions, each capable of taking an argument and returning a value (the specifics don't matter): function convertToNumber(input: string): number { return parseInt(input) } function convertToBoolean(input: number): boolean { ...

Angular Testing: Simplify module setup by using Testbed in each test suite

Currently, I am utilizing a third-party Angular component library that consists of widgets built on web components. It takes approximately 3 seconds for all the web components to be registered. Each time I need to run a test, I have to wait for the librar ...