Assigning value to a member variable in a TypeScript Angular class

Currently, I am in the process of learning Angular. To enhance my skills, I am developing a simple web application using Angular and Spring Boot. One challenge I encountered is assigning a variable to the member variable of a Class.

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';


export class UserCred{
  constructor (
    public username: string,
    public password: string
  ){}
}

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

  public userCred : UserCred


  constructor(
    private http: HttpClient
  ) { }
 
    public createUser(user){
      return this.http.post("http://localhost:8080/restapi/users",user);
    }

    public postUserCredientials(username, password){
      console.log("Service login");
      this.userCred.username = username;
      this.userCred.password = password;
      console.log("class username : ",this.userCred.username);
      return this.http.post("http://localhost:8080/restapi/login", this.userCred);
    }

I faced an issue while trying to assign the value:

this.userCred.username = username; this.userCred.password = password;

The values for username and password that I attempted to assign are sourced from another component. These values were obtained using [(ngModel)] from the HTML file.

Error


ERROR TypeError: Cannot set property 'username' of undefined
    at UserRegistrationService.postUserCredientials (user-registration.service.ts:30)
    at LoginComponent.handleLogin (login.component.ts:39)
    at LoginComponent_Template_button_click_8_listener (login.component.html:8)
    at executeListenerWithErrorHandling (core.js:15216)
    at wrapListenerIn_markDirtyAndPreventDefault (core.js:15251)
    at HTMLButtonElement.<anonymous> (platform-browser.js:582)
    at ZoneDelegate.invokeTask (zone-evergreen.js:399)
    at Object.onInvokeTask (core.js:27476)
    at ZoneDelegate.invokeTask (zone-evergreen.js:398)
    at Zone.runTask (zone-evergreen.js:167)

Answer №1

To fix the error, make sure to initialize the variable that has only been declared in the provided code.

For example:

export class UserRegistrationService {
  public userCred: IUserCred = {
     username: '',
     password: ''
   }

Additionally, consider creating an interface instead of a class if you simply want to specify a type.

export interface IUserCred { // Consider adding "I" as a prefix to UserCred for clarity on whether it's an interface or class.
 username: string;
 password: string;
}

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

Transitioning from an npm package to an npm symbol link in Angular libraries: A step-by-step guide

In my Angular setup, I have a single Application and one Library. The library is connected to the application through a symbolic link (npm link my-lib). I updated my tsconfig.json file to recognize the path of my library: "paths": { "my-l ...

Angular's Bootstrap Array: A Powerful Tool for Organizing

Why does an Angular module have a bootstrap array with more than one component listed? Is there a specific example where multiple components in the bootstrap array are necessary? I'm unsure about this concept and would appreciate any insights or examp ...

What is the best way to transfer the data from one JavaScript object to a new, empty object?

My Angular site requires a JavaScript object (JSON retrieved from a database) to display widgets: [{'widget_id':'1','widget_name':'Blue Widget','widget_description':'A nice blue widget','wid ...

Having issues with your Typescript in Sublime Text?

The issue with the TypeScript plugin in Sublime Text (version 3126) suddenly arose without any identifiable cause. It seems that the plugin no longer recognizes types, resulting in disabled error highlights and autocompletions. This problem occurred on M ...

reCAPTCHA v3 - Alert: There are no existing reCAPTCHA clients available

After coming across a similar issue on Stack Overflow (link to the question here), I attempted to implement reCAPTCHA on my website to combat spam emails received through the form. Despite following Google's instructions, I encountered an error that p ...

Exploring Typescript: Enhancing the functionality of `export = Joi.Root`

I've noticed that the types for @hapi/joi appear to be outdated - some configuration parameters mentioned in the official documentation are missing from the types. To address this, I am attempting to enhance the existing types. node_modules/@types/ha ...

Display HTML instead of text in print mode

Hello, I need help with printing HTML code, specifically an iframe. When I try to add my HTML iframe code, it only prints as plain text. I want to be able to see the actual iframe with its content displayed. Thank you. <script> const messages = [&apo ...

Error Message: Unexpected character "C" found in JSON response from Ionic 2 Http GET request

Trying to execute a GET request and extract data from the response. this.http.get('http://localhost:8888/maneappback/more-items.php').subscribe(res => { console.log(res.json()); }, (err) => { console.log(err); }); An error message ...

When utilizing the dojox.grid.enhanceGrid function to delete a row, the deletion will be reflected on the server side but

I have a grid called unitsGrid that is functioning correctly. I am able to add and delete rows, but the issue arises when I try to delete rows - they do not disappear from my unitsGrid. I have spent hours trying to debug the code but I cannot seem to fin ...

Having trouble pinpointing the specific custom exception type when using the throw statement in TypeScript?

I have run into a problem while using a customized HttpException class in TypeScript. Let me show you how the class is structured: class HttpException extends Error { public status: number | undefined; public message: string; public data: any; ...

Agents should only be initialized within a before function or a spec in Angular

Having trouble with my private function: private GetChargesByClient(clientId: number): Observable<any[]> { const ds = new Date(); const dateTocompare = new Date(ds.setFullYear(ds.getFullYear() - 1)); return this.getCharges(id).pipe(map(res => re ...

Troubleshooting Angular2: How to fix a component that isn't printing anything to the console

I am encountering an issue with my component's code where none of the versions seem to be functioning properly. When I check the console in the browser, it appears blank. export class AssetsComponent { s = 'Hello2'; constructor() { ...

The outer DIV will envelop and grow taller in conjunction with the inner DIV

Could use a little help here. Thank you :) I'm having trouble figuring out how to get the outer div to wrap around the inner div and expand upwards with the content inside the inner editable div. The inner div should expand from bottom to top, and t ...

The table appears to be fixed in place and will not scroll, even though the data

Previously, my code was functioning perfectly with the mCustomScrollbar I implemented to scroll both vertically and horizontally on my table. However, while revising my jQuery code for organization purposes, I seem to have unknowingly altered something tha ...

I am having trouble with a property that I believe should be recognized but is not

Here is the vocabulary I am working with: type MyHeaders = { Authorization: string; Accept: "application/json"; }; type MyGetOptions = { url: string; json: true; }; type MyOptionsWithHeaders = { headers: MyHeaders; }; type MyPostOptions ...

Is there a way to delete a field from a JSON object using JavaScript?

Searching for a way in Node.js to eliminate the date and operation fields from the database. Any suggestions on how to do this? Currently, all fields are being transferred to the FE. The collection pertains to MongoDB. collection.find({'recordType&ap ...

Can an onSnapshot event be set up for an array in order to track changes?

In my system, each user is associated with multiple groups. Each user's group membership is stored as an array within their user document. Additionally, there is a tasks collection where each task contains an array of authorizedGroups that correspond ...

How can you ensure a code snippet in JavaScript runs only a single time?

I have a scenario where I need to dynamically save my .env content from the AWS secrets manager, but I only want to do this once when the server starts. What would be the best approach for this situation? My project is utilizing TypeScript: getSecrets(&qu ...

Restoring scroll position in Next.js when the page is reloaded

Problem Description I am facing an issue with the sticky header functionality I have implemented. It relies on a useEffect hook to monitor its scroll Y offset state. However, when I reload the page, it fails to detect the position until I manually scroll ...

Leveraging jQuery or javascript to display json data in a table with multiple columns

My goal is to convert a JSON data into an HTML table that dynamically creates columns based on the content of the JSON. However, I am facing challenges in looping through the JSON and rendering multiple columns when necessary. The desired output for the e ...