Upon executing a console.log on the class, it comes back as null

Creating a class named UserData to retrieve input values from forms, I then create another class called LoginData with the same values but for a different purpose. When I console.log userData, everything works fine. However, when I try to console.log loginData, it shows as null.

constructor(private alertCtrl: AlertController, public navCtrl: 
    NavController, public navParams: NavParams, public authService: 
    UserProvider, public loadingCtrl: LoadingController, private toastCtrl: 
    ToastController) { 

    console.log(this.loginData)
}

userData = {
    "name":  "",
    "email": "" ,
    "Type_Id" : "", 
    "Mobile" : "",
    "password": "",
};

loginData = {
    UserEmail: this.userData.name ,
    Password:  this.userData.email
}

signup(){
  this.showLoader();
  console.log(this.loginData)

  this.authService.postData(this.userData,'Regestier').then((result) => {
    var userinfo = this.responseData;

    console.log(this.responseData);
    localStorage.setItem('userinfo', this.responseData);

    this.login()
    /* if (this.responseData.Type_Id = "1"){
    this.navCtrl.push(CompanyProfilePage, {}, {animate: true, direction: 
    'forward'});
    }
    else
    {
      this.navCtrl.setRoot(DashboardPage, {}, {animate: true, direction: 
      'forward'});

    }*/

    this.loading.dismiss();
    this.presentPrompt()
 },

 (err) => {
   // Error log
    this.loading.dismiss();

  });

}

I aim to use UserData to save sign up form Data and LoginData for storing login Data. While sign up is functioning correctly, there seems to be an issue with loginData returning null.

Answer №1

Make sure to place your userData and loginData within the constructor function.

export class MyComponent {

  userData; loginData;

  constructor(public navCtrl: NavController) {

    this.userData = {
      "name":  "",
      "email": "" ,
      "Type_Id" : "", 
      "Mobile" : "",
      "password": "",
    };

    this.loginData = {
      UserEmail: this.userData.name ,
      Password:  this.userData.email
    };
  }

  ngOnInit() {

    console.log(this.loginData);
  }

}

example

Answer №2

Your declaration process requires some adjustments to be more effective.

Utilize the Angular lifecycle hook ngOnInit() for handling your declarations:

ngOnInit(){
    this.loginData = {
       UserEmail: this.userData.name ,
       Password:  this.userData.email
    }
}

The Constructor serves as a default method in a class that runs upon instantiation to ensure proper initialization of fields within the class and its subclasses.

ngOnInit is a life cycle hook triggered by Angular2 once it completes building the component.

Answer №3

Utilizing Reactive forms is a straightforward process. Start by importing them into your app.module.ts file:

import { ReactiveFormsModule, FormsModule } from '@angular/forms';

Then, include them in the imports array like this,

  imports: [ BrowserModule, FormsModule, ReactiveFormsModule ],

Your component.ts file can resemble the following :

import { Component } from '@angular/core';
import { FormGroup,FormControl,FormBuilder } from '@angular/forms';

 @Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent  {
 name = 'Angular';
 userData:FormGroup;
 constructor(fb:FormBuilder){
this.userData = fb.group({
  name : new FormControl(''),
  email : new FormControl(''),
  Type_Id : new FormControl(''),
  Mobile : new FormControl(''),
  Password : new FormControl(''),
 })
}

signup(){
console.log(this.userData.value.email);
console.log(this.userData.value.Password);
 }
}

Next, your component.html file can be structured as follows:

<form [formGroup]="userData" (ngSubmit)="signup()">
 <input type="text" formControlName="email">
 <input type="password" formControlName="Password">
 <button (click)="signup()">signup</button>
</form>

By following these steps, your code should run smoothly. Dive deeper into reactive forms for even more functionality!

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

Is it possible to create dynamic meta tags in Angular that will appear in a Twitter-style card preview?

My project involves building a dynamic website using a Java app that serves up a REST-ish JSON API along with an Angular9 front end. A key requirement is the ability to share specific URLs from the app on platforms like Twitter and Slack, which support Twi ...

Converting "promises" to "string" using static methods in TypeScript

I am struggling with incorporating "promises" into my TypeScript code. I am currently developing an e2e testing framework using Protractor and TypeScript, and I need to make database queries to retrieve data for filling forms or performing validations. To ...

Employing Angular CLI for reverse proxying to an API Gateway/lambda service

I'm attempting to reverse proxy Angular by utilizing the proxy.conf.json file to connect to a lambda function behind API gateway. { "/api/profile/*": { "target": "http://asdasdfsdf.execute-api.ap-southeast-2.amazonaws.com", "secur ...

Struggling with making the Angular directive compatible with ng-container

Below is the code snippet where the ng-if condition is not behaving as anticipated If the value of displayGroup is D, it should display the first and second blocks. Can you spot any error in my logic? <div *ngIf="(bookTravelInfo.displayGroup | upp ...

What is the reason for not requiring checks with Union Types when utilizing a variable, yet necessitating them within a function?

Currently working on some Typescript challenges and encountered a scenario involving a union type. In this example, the function getIstanbulPostalCode is declared to return either a string or a number: function getIstanbulPostalCode(): string | number { ...

Multiple consecutive XHR requests failed without any error message. The cause remains unknown

Here is the content of my package.json file: canActivate in my code:</p> imports: [ BrowserModule, FormsModule, ReactiveFormsModule, RouterModule.forRoot([ {//route configs path: '', redirectTo: '/cfbsetup', pathMatch: &a ...

ngx-slick-carousel: a carousel that loops infinitely and adjusts responsively

I have implemented ngx-slick-carousel to showcase YouTube videos in my project. However, I am facing two main issues. Firstly, the carousel is not infinite, and when the last video is reached, there appears to be white spaces before it loops back to the fi ...

styles.css is generating an ERROR message, indicating that it is unable to read properties of null when trying to access the 'classList'

Hey there, I've been working on adding a background color change to my navbar when the scrollY exceeds 30px, and it's functioning properly. However, I'm encountering an error in the console which states that the new classList cannot be added ...

Managing type declarations for two separate yet interlinked projects involves careful attention to ensure consistency and compatibility

My front-end work involves two projects where JavaScript objects from Project 1 are utilized in Project 2. As of now, I have included all the types and methods available in Project 1 into the index.d.ts file of Project 2. However, if I happen to modify a ...

Issues with incorrect source path in Typescript, Gulp, and Sourcemaps configuration

In my nodejs app, the folder structure is as follows: project |-- src/ | |-- controllers/ | | |`-- authorize-controller.ts | |`-- index.ts |--dist/ | |--controllers/ | | |`-- authorize-controller.js | | |`-- authorize-controller.js.map | ...

Utilizing .js file alongside declaration files .d.ts in Angular: A guide

I am facing an issue with my Angular 7 app where I need to include some typed JS constants from outside of the project. These constants are essential for the AngularJS app and need to be kept in a separate js file. I have defined a new path in the tsconfig ...

The validation for the prop 'setLoading' is not defined

Currently, I am utilizing React version 17.0.2 along with Typescript for my project. My aim is to transfer the setLoading function from the parent component (App) to the child component (About) so that the loading state within App can be altered from About ...

Prisma queries are not automatically inferring Typescript types

In my Prisma schema, I have defined the following model: model User { id String @id @default(uuid()) name String email String @unique } After writing the TypeScript code below, I expected the return type o ...

Regular expressions are effective tools, but they may not be as functional within an

Trying to validate URLs using a regex has been tricky. The regex I have works perfectly fine on regex101.com, but for some reason it keeps failing validation when implemented in my Angular field. I'm at a loss as to how to tweak it so that Angular wil ...

Calculate the date and time three months before or after a specified date

I have the following start date : 2023-09-03T00:00:00+05:30 and end date : 2023-09-10T00:00:00+05:30 My objective is to deduct 90 days from the start date and add 90 days to the end date Afterwards, I need to convert it to UTC format In order to achieve ...

How can you effectively structure the routing between Angular2 and Laravel5?

My interactions involve L5 and A2. For L5, I have two routes: '/' (base) and '/edit'. As for A2, there are also two routes: '/' (base) and '/edit' (name: 'Edit'); Upon loading the blablabla.com page, Angu ...

The command 'ng' for Angular is not being detected as a valid internal or external command, executable program, or batch file, preventing access to the Angular app from outside the localhost

Whenever I try to run "'ng' is not recognized as an internal or external command, operable program or batch file." with ng serve --host 0.0.0.0 from my command prompt, it gives me this error message. However, running it through the node.js comma ...

Innovative approaches to enhancing Feathers services through the use of relational data in design patterns

I'm in the process of developing a straightforward application that involves a one-to-many relationship between data entities. Specifically, I am working with feathers js and sequelize (utilizing sqlite) to create a system where each site can have mul ...

Confusion arises from the error message 'No overload matches this call'

Currently, I am working on a weather application using Angular based on the concepts from the book Angular for Enterprise-Ready Web Applications - Second Edition. I am in the process of adding a search component to the app, which will allow users to displa ...

Leverage a variety of environment files

In my Angular 7 project, I am working with the environment.prod.ts file that looks like this: export const environment = { production: true, apiBaseUri: 'https://api.xyz.com' }; Now, I am facing the task of deploying this application on two ...