Error: The specified property is not found on the object in Ionic TypeScript

I am facing an issue while trying to define a todo object that stores members' usernames and passwords with data fetched using ngmodel. Despite my efforts, I have not been able to successfully initialize this object. I attempted to utilize arrow notation in the logForm function to set this up, but it appears to be ineffective. It seems like the problem lies in the incorrect declaration of the todo object.

import { Component, OnInit } from '@angular/core';

import {BackendDataService} from '../../backend-data.service';

import { map } from 'rxjs/operators';

import { Router } from '@angular/router';

import {LocalStorageService} from '../../local-storage.service';


@Component({
  selector: 'app-loginform',
  templateUrl: './loginform.component.html',
  styleUrls: ['./loginform.component.scss'],
})
export class LoginformComponent implements OnInit {



  
  username: string;

  password: string;
  
  todo: Todo;

  /*
  todo = {

  }
  */


  constructor(private backendDataService: BackendDataService, private router: Router, private storage: LocalStorageService) { 
  //constructor = (private backendDataService: BackendDataService, private router: Router, private storage: LocalStorageService) => {
  
    this.todo = new Todo();
    
    
  
  
  }

  ngOnInit() {

  }
  


  

  
  





  //logForm() {
  logForm = () => {


    var obv;



    //var username;
    //var password;
    let username = "";
    let password = "";

    username = this.todo.username; //<<<<ERROR Property 'username' does not exist on type '{}'.
    password = this.todo.password;

    console.log("username: " + username);
    console.log("password: " + password);




    this.storage.set("username", username);
    this.storage.set("password", password);

    obv = this.backendDataService.postLogin(username, password);

    obv.pipe(map( res => res)).subscribe(data => {

        console.log( data.response);

        console.log("isAuthenticated: " + data.isAuthenticated);

        if (data.isAuthenticated == true)
        {
          console.log("response was successful");


            this.router.navigateByUrl('/home');
            //this.router.navigate(['/home']);

        }

        //console.log(data);

        //console.log(data.balance);

        //this.balance = data.balance;

        //this.name = "elephant";

        //this.bitcoinAddress = data.bitcoinAddress;

    });

    

    
  }

}


class Todo
{

  username: string;

  password: string;
  
  test() {
  
    console.log("TEST RAN<<<<");
  
  }


}

Answer №1

Avoid unnecessary steps.

Create a new Todo object without this line of code:

You can directly include the following HTML code:

<input [(ngModel)]="todo.username" />
<input [(ngModel)]="todo.password" />

In your TypeScript file, you can access properties without initializing the object first.

console.log("username: " + this.todo.username);
console.log("password: " + this.todo.password);

this.storage.set("username", this.todo.username);
this.storage.set("password", this.todo.password);

Avoid writing unnecessary code like this:

let username = "";
let password = "";

username = this.todo.username;
password = this.todo.password;

Lastly, consider using a simple function instead of an arrow function:

loginForm(){
  // code here
}

Answer №2

Give this a shot.

Delete this initial line. todo: Todo;

Next define todo in this manner.

todo = {
 username: '',
 password: ''
}

Experiment without relying on the Todo class.

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

Creating a TypeScript module declaration for exporting a class

Just starting out with TypeScript and running into issues while trying to load an es6 javascript module. Here's the code snippet from my javascript file: //TemplateFactory.js export class TemplateFactory{ static getTemplate(module){ } } In ...

Testing Material-UI's autocomplete with React Testing Library: a step-by-step guide

I am currently using the material-ui autocomplete component and attempting to test it with react-testing-library. Component: /* eslint-disable no-use-before-define */ import TextField from '@material-ui/core/TextField'; import Autocomplete from ...

What is the best way to get my Discord bot to respond in "Embed" format using TypeScript?

I've been attempting to create a bot that responds with an embedded message when mentioned, but I'm running into some issues. Whenever I run this code snippet, it throws an error in my terminal and doesn't seem to do anything: client.on(&apo ...

What is the best method for transferring chosen items to a different multiple select using Angular?

How can I transfer selected items to another list, in order to manipulate the final object/array later on? student.component.ts: students= []; studentsFinal = []; onGetStudents() { this.studentService.getStudents() .subscribe( (s ...

Limit potential property values based on the existing keys within the object

My structure looks like this: export interface AppConfig { encryptionKey: string; db: TypeOrmModuleOptions; } export interface BrandsConfig { /** * Brand name */ [key: string]: AppConfig; } export interface IConfig { brands: BrandsConfig ...

Unable to use the toDateString() method on a JavaScript Date object

I've encountered an issue that I need help understanding. My goal is to convert a date into a more user-friendly format using the toDateString() method. However, I keep receiving an error message stating "toDateString() is not a function." Currently, ...

How to traverse a JSON file using TypeScript within an Angular application?

[ { "title": "Marker 1", "innercontent": "the Porcelain Factory" }, { "title": "Marker 2", "innercontent": "The Taj Mahal " }, { "title": "Marker 3", ...

There has been no answer provided. Could this be due to being utilized in an asynchronous function that was not returned as a promise?

I encountered the following error message: Error: No response has been set. Is this being used in an async call that was not returned as a promise to the intent handler? at DialogflowConversation.response (/user_code/node_modules/actions-on-google/dis ...

Exploring generic types using recursive inference

The scenario: export type SchemaOne<T> = | Entity<T> | SchemaObjectOne<T>; export interface SchemaObjectOne<T> { [key: string]: SchemaOne<T>; } export type SchemaOf<T> = T extends SchemaOne<infer R> ? R : nev ...

Error: The current call does not match any existing overloads - TypeScript, NextJS, styled-components

I'm facing an issue while trying to display icons in the footer of my website. The error message "Type error: No overload matches this call" keeps appearing next to my StyledIconsWrapper component, causing Vercel deployment to fail. Despite this error ...

When using Typescript type aliases, make sure to let Intellisense display the alias name instead of the source

Take a look at this brief code snippet type A = number; declare function f(): A; const a = f(); // `a` is number, not A What could be the reason for TS displaying a: number instead of a: A? ...

Embrace the power of npm package within the Nest Framework

Is there a way to integrate the celebrate NPM package with the Nest Framework? The documentation only mentions the use of the class-validator package, but I have experience using the celebrate middleware for request validation in Express and other framew ...

An improved approach for implementing ngClass condition in Angular components

Searching for a more concise way to rewrite the following condition: [ngClass]="{ 'class1': image.isAvailable && (image.property !== true && !null), 'class2': image.isAvailable && ...

Implementing Typescript with React: Assigning event.target.name to state

I am facing an issue with a React state that has specific named keys defined in an interface... Despite trying a potential solution based on the state keys, I am still encountering an error... { [x: string]: string; }' provides no match for the sign ...

TypeScript test framework for testing API calls in VS Code extensions

My VS Code extension in TypeScript uses the Axios library for API calls. I have written tests using the Mocha framework, which are run locally and through Github Actions. Recently, I integrated code coverage reporting with `c8` and I am looking to enhanc ...

Apollo Client is not properly sending non-server-side rendered requests in conjunction with Next.js

I'm facing a challenge where only server-side requests are being transmitted by the Apollo Client. As far as I know, there should be a client created during initialization in the _app file for non-SSR requests, and another when an SSR request is requi ...

What methods can I use to create fresh metadata for a search inquiry?

On my search page, I am using a search API from OpenAI. My goal is to modify the meta description of the page to display 'Search | %s', with %s representing the decoded search query. However, due to limitations in Nextjs 13, the useSearchParams f ...

Angular 8 - How to properly await a promise's completion within a loop before moving on to the

I have a list that needs to be iterated through, with each iteration dependent on the completion of the previous one. Each iteration returns a promise. Currently, my code processes the list quickly without waiting for the promises to resolve: this.records ...

What is the reason for encountering a TypeScript error when using a union type?

interface Bird { age:string, eat:()=>any } interface Fish { age:string, swim:()=>any } type Pet = Fish | Bird; everything looks good so far, defining a Pet type const pet:Pet={ age:"sd", eat:()=>{} } when trying to return ...

Troubleshooting issue with Material UI icons in React application with Typescript

I created a set of icons based on a github help page like this: const tableIcons = { Add: forwardRef((props, ref) => <AddBox {...props} ref={ref} />), DetailPanel: forwardRef((props, ref) => ( <ChevronRight {...props} ref={ref} /> ...