Property undefined with all alert points filled

According to the console, I am facing an issue while trying to route to the dashboard after logging in because the surname property is undefined. However, when I check my alerts, I can see that it is filled correctly at all times.

login(surName: string, passWord){    
    const name = this.members.find( x => x.surname === surName)
    const pass = this.members.find( x => x.password === passWord)
    if(name && pass){
      for (const element of this.members) {
        if(element.surname === surName){
            alert(element.surname + surName);
            this.persist.setPersistence(surName, element.color);
            alert("You are Logged in" + element.surname + element.color);
            this.router.navigate(['/dashbaord']);
            return;
        }
    }
    }else{
      alert("User Details are incorrect please make sure your username and password is correct");
  }
}

I have checked from the point where data is being entered to when the login button is pressed and the values being passed into the set function. This is where the error occurs despite me being able to see the value, so I am puzzled about what might be happening

import { Injectable } from '@angular/core';
import { Persistance} from '../Persistance/persistance.model'

@Injectable({
  providedIn: 'root'
})
export class PersistService {
  persist: Persistance;
  constructor() { }

  setPersistence(surname : string, color: string){
    alert(surname);
    this.persist.surname = surname;
    this.persist.color = color;
  }
}

The Error:

core.js:4197 ERROR TypeError: Cannot set property 'surname' of undefined

Although I can observe the property being defined at all points where it's assigned or used, I'm still unable to understand why this error is occurring

Answer №1

Consider using the following code snippet:

data = DataStorage {};

This piece of code should work for you. Your data structure has not been properly set up yet, therefore you are unable to assign any values to its properties.

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

What is the best way to update the color of a label in a Mantine component?

When using the Mantine library, defining a checkbox is done like this: <Checkbox value="react" label="React"/> While it's possible to change the color of the checkbox itself, figuring out how to change the color of the label ...

Exploring the power of TypeScript strictNullChecks with array manipulation

My understanding of Typescript's behavior with the compiler option strictNullChecks enabled is not yet complete. It appears that in some cases, Typescript (version 2.4.1) recognizes an item in a string[] as a string, while other times it does not: in ...

Issue: StaticInjectorError(DynamicTestModule)[FilterOptionsComponent -> Environment]:

While testing my app, I encountered an error that stated: "PhantomJS 2.1.1 (Linux 0.0.0) FilterOptionsComponent should clean fields when click in the clean button FAILED Error: StaticInjectorError(DynamicTestModule)[FilterOptionsComponent -> Environ ...

Incorporating a component specified in a .jsx file into a TypeScript file

We recently acquired a react theme for our web application, but ran into issues transpiling the components. After resolving that problem, we are now facing type-related challenges. It seems that TypeScript is struggling because the props do not have a def ...

Error: The window object is not defined in NextJS

I've encountered an issue while trying to build the app for production. The error message states: ReferenceError: window is not defined. I'm struggling to find a solution. FullCode: const [windowSize, setWindowSize] = useState<WindowInfo>( ...

Refreshing a component without having to reload the entire page in Angular4: A step-by-step guide

I have an application built with Angular 4 that consists of two components - one for adding items and another for viewing them. I am facing an issue where the view page does not update with the new item added. Although I can see the updated data source, th ...

When utilizing *NgIf, the button will be shown without the accompanying text being displayed

When trying to display either a confirm or cancel button based on a boolean set in my component.ts, I implemented the following code in my HTML: <mat-dialog-actions class="dialog-actions"> <button class="cancel-btn" ...

Is there a way to remove a dynamically rendered component from a list?

Whenever I click a button, the same component is dynamically rendered on top of the list. But now, I need to implement a feature where users can delete any component from the list by clicking a cancel button associated with each component. Here's my ...

Issue arising from swiper version 8 compatibility with angular version 16

After upgrading my Angular application to version 16 and implementing swiper version 8, I encountered errors when running the build:ssr command. The specific error message I received was: ./src/app/modules/pages/enterprise-price-list/enterprise-price-list. ...

Error encountered when attempting to open PDF documents located in the ./../../../assets/pdf/file.pdf directory. Route matching failed, resulting in inability to access the

In my Angular application, I have stored the PDF file under the assets/pdf directory. Here is the code snippet: <div class="container-fluid mt-2 mb-2"> <a target="_blank" href="./../../../assets/pdf/MSW - Transition Briefing Slides v1.1.pdf"& ...

Utilize Typescript to inject types into a library

I have a code snippet that reads data from a JSON file and creates a type based on it, which is then used for further operations. import jsonData from './mydata.json' type CustomType = typeof jsonData .... This process ensures that the generate ...

Maintaining checked items in their original state while searching for another one in ion-searchbar can be achieved by properly handling

My goal is to maintain the checked items as checked when searching for another item in ion-searchbar. While I have managed to keep the checked items, the checkmark icon does not stay checked. What I aim for is to retain the checked state of all food items ...

Implementing Typescript for managing state in React components

Currently, I have a state set up like this: const [newInvoice, setInvoice] = useState<InvoiceType | null>(invoice) The structure of my InvoiceType is as follows: customer_email: string customer_name: string description: string due_date: stri ...

The datepicker in Angular Material refuses to open when used within a modal dialog box

I successfully integrated an angular material 2 date-picker into a bootstrap modal form: <div class="modal-dialog modal-lg"> <div class="modal-content"> <div class="modal-header"> <h4 class="modal-title">{{title}}</h ...

Creating a component in the libs using Angular schematics with Webstorm

After setting up an angular project in nx monorepo, I encountered a problem when creating UI libraries and attempting to utilize the "Angular Schematic" feature. Despite following the steps as shown in the provided image, the generated files were still bei ...

The NullInjector has issued an error regarding the lack of a provider for the Decimal

I recently integrated lazy loading into my application. However, one of my services is in need of the DecimalPipe. The structure of my modules goes like this: service -> shared module -> App module To give you more context, I have already added "Co ...

Combining Spring Boot and Angular applications for seamless integration

I am trying to connect my Spring Boot application with an Angular application that are running on different servers. When attempting to access REST API from the Angular app, the API call is successful but I encounter an error response on the UI. Acc ...

Avoid repeating the base URL when creating services using the intercept service concept

Greetings, I must begin with an apology for any confusion in my explanation of the issue at hand. Currently, as part of a project I am working on, the Base URL or Environment URL is defined within the InterceptService. However, there seems to be an anomal ...

Mastering Typescript lookup types - effectively limit the properties included in a merge operation with the Partial type

Exploring lookup types, I'm interested in creating a safe-merge utility function that can update an entity of type T with a subset of keys from another object. The objective is to leverage the TypeScript compiler to catch any misspelled properties or ...

Can you explain why it prints to the console twice every time I try to add an item?

This is a note-taking application created using Angular and Firebase. The primary functionalities include adding items and displaying them. I noticed a strange behavior where my ngOnInit() method is being called twice every time I add an item. As shown in ...