Property ' ' is not defined and cannot be read

Having trouble creating an Angular form and inserting data from the form into SQL Server. When trying to run Angular, I encounter various errors.

"Cannot read property 'UserName' of defined" "Cannot read property 'UserSurname' of defined" along with other similar issues.

In my users-detail.service.ts file, I have formData:UsersDetail

import { Injectable } from '@angular/core';
import { UsersDetail } from './users-detail.model';
import {HttpClient} from "@angular/common/http";

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

  formData:UsersDetail
  
  readonly rootURL = 'https://localhost:51128/api'

  constructor(private http:HttpClient) { }


  postPaymentDetail(formData:UsersDetail){
    return this.http.post(this.rootURL+'/Users',formData);
  }
}

Referencing back to my users-detail.service.ts file, I use UsersDetailClass which is declared as formDataUsersDetail

    export class UsersDetail {

    UserId :number;
    UserName :string;
    UserSurname :string;
    UserEmail :string;
    UserPassword :string;
    UserTypeId :number;
}

Both these files are located in a shared folder within the project structure.

In appModule.ts, you can find

import { UsersDetailService } from './shared/users-detail.service';

and in the imports[] section:

imports: [
    BrowserModule,
    FormsModule,
    HttpClientModule
  ],
  providers: [UsersDetailService],

The users-detail folder contains users-detail.component.ts and users-detail.component.html

Where users-detail.component.ts has:

import { Component, OnInit } from '@angular/core';
import { NgForm } from '@angular/forms';
import { UsersDetailService } from 'src/app/shared/users-detail.service';

@Component({
  selector: 'app-users-detail',
  templateUrl: './users-detail.component.html',
  styles:[]
})
export class UsersDetailComponent implements OnInit {

  constructor(private service:UsersDetailService) {}

Finally, in users-detail.component.html there's:

<form #form="ngForm" autocomplete="off" (submit)="onSubmit(form)">
  <input type="hidden" name="UserId" [value]="service.formData.UserId">
  <input type="hidden" name="UserTypeId" [value]="service.formData.UserTypeId">

  <div class="form-group">
    <input name="UserName" #UserName="ngModel" [(ngModel)]="service.formData.UserName" 
    class="form-control" placeholder="UserName" required="">
  </div>

  <div class="form-group">
      <input name="UserSurname" #UserSurname="ngModel" [(ngModel)]="service.formData.UserSurname" 
      class="form-control" placeholder="UserSurname" required>
    </div>

    <div class="form-group">
        <input name="UserEmail" #UserEmal="ngModel" [(ngModel)]="service.formData.UserEmail" 
        class="form-control" placeholder="UserEmail" required>
      </div>

      <div class="form-group">
          <input name="UserPassword" #UserPassword="ngModel" [(ngModel)]="service.formData.UserPassword" 
          class="form-control" placeholder="UserPassword" required>
        </div>
        <div class="form-group">
          <button class="btn btn-success btn-lg btn-block" type="submit" [disabled]="form.invalid">Submit</button>
        </div>
</form>

Compiling Angular shows no errors, but the Chrome console reports:

"Cannot read property 'UserName' of defined".

If anyone can offer any guidance on resolving this issue, it would be greatly appreciated!

Answer №1

Operating in this manner is not the correct approach. It is not possible to directly assign a reference to your service in your view template or component.html.

In your component.html file, simply remove the prefix service. from the ngModel and value attributes for all inputs. This action should be taken because formData is the property defined within your components.

<input type="hidden" name="UserId" [value]="formData?.UserId">
<input type="hidden" name="UserTypeId" [value]="formData?.UserTypeId">

<div class="form-group">
  <input name="UserName" [(ngModel)]="formData?.UserName" class="form-control" placeholder="UserName" required="">
</div>

<div class="form-group">
  <input name="UserSurname" [(ngModel)]="formData?.UserSurname" class="form-control" placeholder="UserSurname" required>
</div>

<div class="form-group">
  <input name="UserEmail" [(ngModel)]="formData?.UserEmail" class="form-control" placeholder="UserEmail" required>
</div>

<div class="form-group">
  <input name="UserPassword" [(ngModel)]="formData?.UserPassword" class="form-control" placeholder="UserPassword" required>
</div>

In your user-detail.component.ts file, you can initialize the formData property with an empty object or set specific properties with default values (can be empty strings or based on business logic). The formData property stores all form data thanks to 2-way data binding.

export class UsersDetailComponent implements OnInit {

  formData: UsersDetail = undefined;

  constructor(private service:UsersDetailService) {}

  onSubmit() {
    console.log(this.formData);
    this.service.postPaymentDetail(this.formData).subscribe(response => {
      console.log(response);
    }) 
  }

}

Upon calling the onSubmit() method, the formData will be passed as parameters to the postPaymentDetail() method.

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

Rounding Decimals using JavaScript

I am facing the challenge described in this particular query. In most cases, my code works fine to round numbers to two decimal places with the following formula: Math.round(num * 100) / 100 However, there was a peculiar scenario where it failed. When tr ...

Leverage the child interface as a property interface containing a generic interface

I'm facing an issue while trying to incorporate typings in React. The concept is centered around having an enum (EBreakpoint) that correlates with each device we support. A proxy wrapper component accepts each device as a prop, and then processes the ...

The error message "The function XXX.isSupported is not defined" is displayed

Integrating a JavaScript library into Typescript When I use this function in JavaScript, it works perfectly: _clickHandler() { TouchID.isSupported() .then(authenticate) .catch(error => { AlertIOS.alert('TouchID not supported'); }); ...

Unit testing an Angular component that inherits from a base component

While running a basic testcase for one of my components, I encountered an error message. The component inherits from another class. Error: TypeError: Cannot read property 'setParent' of undefined Does anyone have any suggestions on how to resol ...

Switching the checkbox state by clicking a button in a React component

Is there a way to update checkbox values not just by clicking on the checkbox itself, but also when clicking on the entire button that contains both the input and span elements? const options = ["Option A", "Option B", "Option C"]; const [check ...

Slideshow through each item using Typescript and Angular8

I came across a solution in this carousel on by one link, but I'm struggling to work with the jQuery code even though I have JQuery installed in my project. For example: const next = jQuery(this).next(); I am looking to convert the JQuery code from ...

Apollo Angular client that consistently relies on caching

I am currently using the Apollo Angular client along with the InMemoryCache. I have some watchQuery's that I want to disable caching for. I have configured my client in the following way: link: httpLink.create({uri}), cache: new InMemoryCache(), ...

This TypeScript error occurs when the type of a CSS file lacks an index signature, resulting in an implicit 'any' type for the element

Currently in the process of transitioning a React app to utilize Typescript. Encountering an error message that reads: ERROR in [at-loader] ./src/components/Services/Services.tsx:34:29 TS7017: Element implicitly has an 'any' type because typ ...

Is there a way to utilize Angular in identifying whether a given value corresponds with the value of a particular radio button within my application?

I have an array of lists that I need to display in radio buttons. Like this: https://i.stack.imgur.com/cmYgO.png https://i.stack.imgur.com/Zx4bm.png https://i.stack.imgur.com/jBTe3.png My goal is to have a checkbox that matches the values loaded from a ...

What is the best way to bundle my Language Server along with my client?

Currently, I am in the process of developing a language server for VSCode which consists of both a client and a server that communicate over RPC. Fortunately, the official documentation includes a fully functional example, where the language server is div ...

Tips for accessing a route using query parameters without displaying special characters like '?' and '=' in the URL

I am new to Angular routing and I need help implementing it for navigating to a details page when an icon is clicked from the parent component. Below is my code snippet: product.component.ts // Method called when the edit icon is clicked loadSingleRec ...

Joi has decided against incorporating custom operators into their extended features

I am having trouble extending the joi class with custom operators. My goal is to validate MongoDB Ids, but when I try to use the extended object, I encounter the following error: error: uncaughtException: JoiObj.string(...).objectId is not a function TypeE ...

What is the rationale behind Angular's decision to use cdr.markForCheck() instead of cdr.detectChanges() in the async

Regarding Angular, I have a question: Why does the Angular async pipe use cdr.markForCheck() instead of cdr.detectChanges()? I have noticed two main differences between these two approaches: markForCheck() marks the path all the way up to the root compo ...

I am interested in placing a breakpoint on the ng-template

I'm encountering an issue with this line in my HTML code. <ng-template ngFor let-i="index" let-c="count" let-contact [ngForOf]="contacts"> Unexpectedly, the ngFor directive is executing when I don't intend it to. I would like to investig ...

Having Trouble with Ionic 2's Loading Controller

In my attempt to utilize the recently added LoadingController in this scenario: let loading=this.load.create({ content: "Connexion au serveur Migal en cours..." }); loading.present(); this.http.get(this.urlCheckerForm.value.migalUrl+'/action/Mobi ...

Guide to accessing a nested and potentially optional object property with a default value and specifying its data type

Just a simple query here... my goal is to extract data.user.roles, but there's a possibility that data may be empty. In such cases, I want an empty array as the output. Additionally, I need to specify the type of user - which in this instance is any. ...

Verify if a given string exists within a defined ENUM in typescript

I have an enum called "Languages" with different language codes such as nl, fr, en, and de. export enum Languages { nl = 1, fr = 2, en = 3, de = 4 } Additionally, I have a constant variable named "language" assigned the value 'de'. My g ...

The Angular 2 function within the subscribe method is being triggered before the request has finished processing

I have been attempting to extract a parameter from a URL and then passing it to another method. Below is the code snippet: ngOnInit() { this.getParamValues(); } getParamValues() { this.route.queryParams.subscribe(params => { ...

Issue with ngRX infinite loop caused by the updateOne function in the adapter

Hey there, I'm struggling to figure out why my code is stuck in an infinite loop. I've searched online extensively but haven't found a solution that fits my specific issue. This is the code snippet causing the problem: /** * CODE ...

An error occurred when attempting to open a modal from an Angular5 selectbox, triggering an ExpressionChangedAfterItHasBeenCheckedError

Hello Everyone, I encountered an interesting issue and managed to come up with a solution. So, here's the problem: I have a select box with various options. If a user selects a specific option, I display a modal window. However, the problem arises wh ...