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

Encountering a problem while trying to incorporate Mapbox GL JS into an Angular 8 web application

I'm currently working on incorporating mapbox into my simple web application, but I'm encountering difficulties when attempting to add it. At this point, I've already created a mapbox service and a map component. My approach involved using ...

The noUnusedLocal rule in the Typescript tsconfig is not being followed as expected

I am currently working on a project that utilizes typescript 3.6.3. Within my main directory, I have a tsconfig.json file with the setting noUnusedLocals: true: { "compilerOptions": { "noUnusedLocals": true, "noUnusedParameters": true, }, ...

How can I clear the div styling once the onDismiss handler has been triggered

Seeking assistance with resetting a div on a Modal after it has been closed. The issue I am facing with my pop-up is that the div retains the previous styling of display: none instead of reverting to display: flex. I have searched for a solution without su ...

What could be causing the radio button to not be checked when the true condition is met in Angular?

I am working on an angular7 application that includes a dropdown list with radio buttons for each item. However, I am facing an issue where the radio button is not checked by default on successful conditions. Below is the code snippet from my component.htm ...

Combining two streams in RxJS and terminating the merged stream when a particular input is triggered

I am currently developing an Angular application and working on implementing a system where an NGRX effect will make requests to a service. This service will essentially perform two tasks: Firstly, it will check the local cache (sqlite) for the requested ...

The 'in' operator is unable to find 'colour' within true (function return type)

Here's the TypeScript code I'm working with: let a: unknown = true; if(hasColour(a)) { console.log(a.colour); // Using a.colour after confirming a has the colour property } I've created a function to check if the color property exist ...

Unused code splitting chunk in React production build would improve performance and efficiency of

When running the command npm run build, a build directory is generated with js chunks. I have observed an unfamiliar file named [number].[hash].chunk.js that does not appear in the list of entrypoints in the asset-manifest.json file. Instead, this mysteri ...

run a function once ngFor has completed rendering the data

I'm attempting to run a function every time my ngFor finishes loading data from the API. However, the callback only works on the initial load of the ngFor. How can I make sure that the callback is executed whenever my ngFor data changes? I found a ...

Incorporating Angular views as peer components within the current view

I am currently working on implementing this HTML structure: <tr *ngFor="let row of rows"> <expandable-tree-row [columns]="cols" [data]="row"></expandable-tree-row> </tr> Within the ExpandableTreeRo ...

Avoiding the pitfalls of hierarchical dependency injection in Angular 6

Too long; didn't read: How can I ensure that Angular uses the standard implementation of HttpClient in lower level modules instead of injecting a custom one with interceptors? I have developed an Angular 6 library using Angular CLI. This library expo ...

Customizing AxiosRequestConfig with Axios in TypeScript can greatly enhance the functionality and

Currently working with React and Axios. Lately, I've been experimenting with custom configurations in Axios as shown below: import $axios from 'helpers/axiosInstance' $axios.get('/customers', { handlerEnabled: false }) However, wh ...

Angular 9 Issue: Failure to Display Nested Mat-Tree Children

Hello everyone, I'm new to posting questions on Stack Overflow and I'm seeking some assistance with an issue I'm having with Mat-Tree. Despite the fact that my data is present when I console log it, the children are not appearing. I am fetc ...

Searching for a particular Prettier setting

Seeking a Nicer alternative. I am exploring if there is a way to format code like this without moving the first attribute to a new line: <div class="test-class" [test-binding]="true" (test-binging)="test()" ...

Exploring Geofirestore's capabilities with advanced query functionalities

Thinking about updating my firestore collection structure to incorporate geoquery in my app. Geofirestore requires a specific structure: interface GeoDocument { g: string; l: GeoPoint; d: DocumentData; } I understand that geofirestore does ...

Having trouble locating the name 'angular' in TypeScript error message

I have completed all the necessary settings, such as adding the typescript compiler in webstorm and installing tsd with npm. However, I am still encountering an error stating 'Cannot find name Angular'. tsd.json { "version": "v4", "repo": ...

Having difficulty in using pipe to filter records upon clicking the Button

I am having trouble filtering the records as needed. What I want is that when "All" is clicked, no filter should be applied. When any other option is clicked, the filter should be applied. HTML <div class="container " style="padding-top:100px"> ...

An easy guide on incorporating external npm modules into Angular 2, such as an encryption library

Within my Angular 2 application (utilizing the SystemJS module manager and Typescript as the scripting language), I am in need of importing an npm module for encryption purposes. This could be either Crypto-JS, Forge-JS, or any alternative that serves the ...

Methods for setting a global instance within a local function

Hello, I'm fairly new to using TypeScript and Angular2. Let me quickly explain what I'm trying to accomplish with my method. I have some hard-coded XML data that I need to parse into JSON format. Once parsed, each JSON object needs to be assigned ...

I have been encountering an error consistently whenever I attempt to access the _id parameter in my angular front-end

EmployeeComponent.html: 11 ERROR TypeError: Cannot read property '_id' of undefined This is the error I encounter whenever I attempt to access the id in my front-end implementation using Angular. I have attempted incorporating ngIf, but unfo ...

I can't seem to catch my Zod error, even though 'express-async-errors' is already installed. What could be causing this issue?

I've been working on developing an API, but I'm facing issues with setting up a global error controller using Zod. It seems that the global error handler is not being called even though I'm using express-async-errors. Below is my error mana ...