An issue occurred with Ionic 4: TypeError - Unable to access property 'name' as it is undefined

None of the answers to similar questions have provided a solution for me

SITUATION:

I've been setting up a SQL Server connection from my Ionic app. You can check out my previous question for more details

The workflow goes as follows: Ionic connects to ASP.NET MVC, which then links to SQL Server.

I've successfully managed to insert records into the SQL database where the id property auto-increments. However, I'm facing an issue where the name property always ends up being NULL despite passing a string value through ion-input.

ERROR MESSAGE:

ERROR TypeError: Cannot read property 'name' of undefined

at Object.eval [as updateRenderer] (SqlPage.html:17)     
at Object.debugUpdateRenderer [as updateRenderer] (core.js:23936)     
at checkAndUpdateView (core.js:23311)     
at callViewAction (core.js:23547)        
at execEmbeddedViewsAction (core.js:23510)         
at checkAndUpdateView (core.js:23307)       
at callViewAction (core.js:23547)        
at execComponentViewsAction (core.js:23489)         
at checkAndUpdateView (core.js:23312)
at callViewAction (core.js:23547)

Below are the relevant files, if you need access to any additional files, please let me know:

sql.page.html

<ion-header>
  <ion-toolbar>
    <ion-title>sql</ion-title>
  </ion-toolbar>
</ion-header>

<ion-content padding>
  <ion-item>
    <ion-label>Name</ion-label>
  <ion-input type="text" [(ngModel)]="id" hidden></ion-input>
  <ion-input type="text" [(ngModel)]="name"></ion-input>
  </ion-item>
  <ion-button (click)="Add()">Add</ion-button>

  <ion-list>
  <ul>
  <li *ngFor="let items of items">
    {{ item.name }}
  <ion-button (click)="Edit(item)">Edit</ion-button>
  <ion-button (click)="Delete(item)">Delete</ion-button>


  </li>
  </ul>
  </ion-list>
</ion-content>

sql.page.ts

import { Component, OnInit } from '@angular/core';
import { SqlService } from '../../services/sql.service'

@Component({
  selector: 'app-sql',
  templateUrl: './sql.page.html',
  styleUrls: ['./sql.page.scss'],
})
export class SqlPage implements OnInit {
  items=[];
  id: string;
  name: string;

  constructor(public sql: SqlService) { 
    this.getAll()
  }

  ngOnInit() {
  }

  getAll() {
    this.items=[];
    this.sql.getAll().subscribe(data=>{
      for(var i=0;i<data.length;i++){
        this.items.push(data[i]);
      }
    })

  }

  Add() {
    if(this.id==null){
    this.sql.Create(this.name).subscribe(data=>{
      this.name=name;
      this.getAll();
    })
  }else {
    this.sql.Update(this.id, this.name).subscribe(data=>{
      //this.id=null
      this.name=name;
      this.getAll();
    })
  }        
}

  Edit(item) {
    this.id = item.id
    this.name = item.name
  }

  Delete(item) {
    this.sql.Delete(item.id).subscribe(data=>{
      this.getAll()
    })

  }

}

sql.service.ts

import { Injectable } from '@angular/core';
import { Http, Headers, RequestMethod, RequestOptions } from '@angular/http';
import { map } from 'rxjs/operators';

@Injectable({
  providedIn: 'root'
})
export class SqlService {

  url:string="http://localhost:50287/api/APIDemo/"
  constructor(private http: Http) { }

getAll(){
  return this.http.get(this.url).pipe(map(res=>res.json()));
}

Create(name) {
  var body=JSON.stringify({name});
  var header=new Headers({'Content-Type':'application/json'})
  var option=new RequestOptions({method:RequestMethod.Post,headers:header})
  return this.http.post(this.url + "Posttest",body,option).pipe(map(res=>res.json()))
}

Update(id, name) {
  var body={"id":id,"name":name};
  var header=new Headers({'Content-Type':'application/json'})
  var option=new RequestOptions({method:RequestMethod.Post,headers:header})
  return this.http.post(this.url,body,option).pipe(map(res=>res.json()))
}

Read(id) {
  return this.http.get(this.url+id).pipe(map(res=>res.json()))
}

Delete(id) {
  return this.http.delete(this.url+id).pipe(map(res=>res.json()))
}

}

Can anyone assist in explaining why I'm encountering this error message? Any guidance would be greatly appreciated.

Answer №1

There are two issues that need to be addressed in the code:

1 - modify this line within the *ngFor loop:

let items

change it to:

let item 

2 - Inside the SqlPage class, make the following changes:

update

  items=[];
  id: string;
  name: string;

to:

  items=[];
  id: string = "";
  name: string = ""; 

Remember that when a variable is declared in JavaScript, its default value is undefined

Answer №2

To initialize your VAR in the constructor, you can do it this way:

   constructor(public sql: SqlService) { 
        this.getAll();
        this.name = "";
      }

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

The controller is executing the action method two times

My MVC controller's action is being triggered twice by my jQuery code. Upon investigation, I discovered that the link was being activated both by jQuery and the MVC view. $('.treeview-menu li a[name="environments"]').on("click", function () ...

Dynamically generating an Angular component and populating it with data

I am currently working with Angular 7/8 and I have some code that adds a new component dynamically. In the parent component, my .ts file includes the following: PARENT COMPONENT Within the .ts file: @ViewChild(InjectDirective) injectComp: InjectDirect ...

Experiencing a Typescript error when trying to access a property within a nested object

My current challenge involves typing an object, which seems to be error-free until I try to access a nested property and encounter the dreaded red squiggle. After some research, I came across suggestions like this: type FlagValue = string | boolean | numb ...

Angular 2: Export Data to CSV and Download

My backend is built in a Spring Boot application where I am returning a .csv file. @RequestMapping(value = "/downloadCSV") public void downloadCSV(HttpServletResponse response) throws IOException { String csvFileName = "books.csv"; ...

Tips for transferring information between two components when a button is clicked in Angular 2

I am currently working on a code that displays a table on the main page with two buttons, "Edit" and "Delete", for each row. When the Edit button is clicked, a modal opens up. My question is, how can I pass the "employee id" of a specific employee to the ...

Ways to verify that the Google Analytics code is functioning properly within an Angular 2 application

I'm just getting started with Google Analytics and I'm attempting to integrate it into my Angular 2 project. Here's how I've set it up: app.component.ts import { Component } from '@angular/core'; import {Router, NavigationEn ...

Nested function TypeScript declarations

Currently, I am attempting to define a type for my controller function in (nodejs) similar to the following export const registerUser = asyncWrap(async function(req:Request, res:Response, next:NextFunction) { res.status(200).json({ success: true}); }) ...

Ensuring proper extension of Request headers in Typescript

I am having trouble retrieving the userId from req.headers, how can I fix this issue? Initially, I attempted the following: interface ISpot{ thumbnail: File, company: string, price: number, techs: string } interface IReqCustom<T& ...

Implementing Form Validation in Angular 5 and showing errors in a reusable component

My current setup includes a generic component structured as follows: // selector: 'app-text-box' <form> <input type="text" [name]="data.name" [id]="data.name"/> </form> <error-message [message]="message"></ ...

When utilizing the JQuery Ajax Method, the successful submission of data does not occur in the form of an Array

I am having an issue with my Jquery Ajax function that is supposed to get data from an MVC controller. The Ajax method is being called perfectly, but the controller method is hit after the success method in the Ajax call. I am returning an Array from the c ...

Exploring the functionality of Typescript classes in a namespace through Jest testing

Within a certain namespace, I have created a method like so: // main.ts namespace testControl { export const isInternalLink = (link: string) => { return true; } } I also have a jest spec as shown below: // main.spec.ts test('sh ...

Chrome autocomplete behaves as if the input fields are disabled and cannot be clicked on

I am experiencing an unusual issue with autofill in Chrome. After logging in and then logging out of the app, the input fields (email, password) are auto-filled but appear to be frozen and unclickable. This problem does not occur every time; it only happe ...

Looking to retrieve the request body in a route handler in Next.js version 13.2?

I encountered an issue while attempting to send a post request to my API. The problem arises when I try to access the request body within the route handler, resulting in the following error: Code: export async function POST(request: Request) { const ...

Retrieving the final element from a TypeScript JSON array

I am trying to retrieve the value of the "id" property from the last element in an array of JSON objects. While I can easily find each element by id, I specifically need to extract the value of the last "id" in the array of JSON objects. In the example p ...

Rearranging the export order in a barrel file for Angular 2 services can have a significant impact on dependency

After spending some time puzzling over this issue, I'm reaching out for some assistance. In my development workflow, I store all of my core service files in a shared folder that I then combine into a single file named common.ts. These services are i ...

Using Observables for Polling in Angular 8

Greetings, I am in the process of upgrading my project from Angular 5 to Angular 8. Below is the code snippet I used for polling: Observable.interval(this.intervalTime).timeout(600000) .takeWhile(() => this.alive) .subs ...

Angular: Keeping all FormControls in sync with model updates

I am dealing with a collection of FormControls that were created using FormBuilder: this.someForm = this.fb.group({ name: '', size: '', price: '', }); Is there an alternative method to update them based on ...

Setting key-value pairs in TypeScript objects explained

I encountered an issue with setting key/value pairs on a plain object. type getAObjectFn = <K extends string, V>(k: K, v: V) => Record<K, V> const getAObject: getAObjectFn = (k, v) => { return { [k]: v } } console.log(getAObject ...

What could be causing the issue with my React Native app's release version not opening on a physical Android device?

I encountered an issue while trying to install the Release version of my application. In order to test both the debug and release versions on my physical and virtual devices, I utilized the following commands: ./gradlew assembleDebug, ./gradlew assembleRel ...

What is the best way to retrieve all SVG objects within a specific area in an Angular application?

I am currently developing an SVG drawing application and have implemented a tool that enables users to select all shapes within a rectangular area. However, I am facing the challenge of detecting the SVG shapes located underneath the selected rectangle. ...