When attempting to login, I receive a null result and the submit button in Angular 5 is unresponsive

I am facing an issue with login authentication. Upon debugging, I noticed that my Database is returning null, which was not the case before.

I have tried various approaches to identify the bug but have been unsuccessful in locating it.

Interestingly, when I remove the authentication, the console.log works fine before validation. However, within the login method and prior to validation in the if statement, it returns NULL.

DATABASE.SERVICE

import { Injectable } from '@angular/core';
import {User} from '../model/user';
import {serialize} from 
'@angular/compiler/src/i18n/serializers/xml_helper.d';

 @Injectable()
 export class DatabaseService {
 User: User;
  constructor() {
  this.User = JSON.parse(localStorage.getItem('user'));
  }
 login(email:string, password:string):boolean {
   //Here I get UNDEFIEND
   if(email == 'admin' && password == 'admin'){
     this.User = {
      email:'admin',
      password:'admin'
   }
 }
  localStorage.setItem('user',JSON.stringify(this.User));
  return this.checkLogin();
 }
 logOut(): void{
  localStorage.clear();
 }
checkLogin():boolean{
 return (this.User != null);
 }
}

LOGIN.COMPONENT

import { Component, OnInit } from '@angular/core';
import { FormsModule } from '@angular/forms';
import {NgForm} from '@angular/forms';
import {DatabaseService} from '../../service/database.service';
import {Router} from '@angular/router';


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

 constructor(private database:DatabaseService,private router:Router) { }
 onFormSubmit(myForm:NgForm){
if(myForm.valid){
 //Validation Here Works Fine
//Button Action Not Working
  if(this.database.login(myForm.value['email'],myForm.value['password'])){   
    this.router.navigate(['dashboard']);
   }
  }
 }
  ngOnInit() {
  }

 }

HTML LOGIN

<form #myForm="ngForm" (submit)="onFormSubmit(myForm)" method="GET">
<input type="text" name="email" placeholder="Enter email">
<input type="password" name="password" placeholder="Enter Password">
<button type="submit">Log In</button>
</form>
<router-outlet></router-outlet>

USER MODULE

export class User{
email:string;
password:string;
};

Answer №1

Ensure that your login method returns a boolean value.

login(email:string, password:string):boolean {
   if(email == 'admin' && password == 'admin'){
       this.User = {
           email:'admin',
           password:'admin'
       };
       return true;
   }
   return false;
}

It seems like there is an issue with your template. Make sure to bind the model correctly by referring to https://angular.io/guide/forms or https://angular.io/guide/reactive-forms. Update your template as follows:

<form #myForm="ngForm" (submit)="onFormSubmit(myForm)" method="GET">
<input type="text" name="email" [(ngModel)]="email" placeholder="Enter email">
<input type="password" name="password" [(ngModel)]="password" placeholder="Enter Password">
<button type="submit">Log In</button>
</form>
<router-outlet></router-outlet>

Additionally, adjust your component as shown below:

import { Component, OnInit } from '@angular/core';
import { FormsModule } from '@angular/forms';
import {NgForm} from '@angular/forms';
import {DatabaseService} from '../../service/database.service';
import {Router} from '@angular/router';


@Component({
 selector: 'app-login',
 templateUrl: './login.component.html',
 styleUrls: ['./login.component.scss']
})
export class LoginComponent implements OnInit {
 email: string;
 password: string;

 constructor(private database:DatabaseService,private router:Router) { }
 onFormSubmit(myForm:NgForm){
if(myForm.valid){
  if(this.database.login(this.email, this.password)){   
    this.router.navigate(['dashboard']);
   }
  }
 }
  ngOnInit() {
  }

 }

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

Loop through keys of an object using *ngFor

I have an object structured like this "Stage" : { // -> vaga.stage "ID01" : { // -> stage.code "abeb5220-2003-4b8b-a6d5-853a40ca7d60" : { //candidate "email" : "<a href="/cdn-cgi/l/email-protectio ...

Encountered an issue with Angular: Unable to set value for null property 'setValue'

Want to set a value in the fileInfo of my code. This is what I have: this.welderCreationForm.controls['wpsQualified'].value[index]['fileInfo'].setValue(data._id); FormControl reference: ...

Problem of Restricting Array to Single Element at Once

I seem to be facing an issue with a seemingly straightforward function that creates an array - and I'm unable to pinpoint the root cause of the problem. It's probably something simple, but for some reason, it eludes me. Here is the function in q ...

Encountering TS2339 error while attempting to append a child FormGroup within Angular framework

I'm currently working with Angular8 and facing an issue while attempting to include a child FormGroup to a form using the addControl method: this.testForm = new FormGroup({ id: new FormControl(0), people: new FormGroup({ } ...

Is it possible to apply a style change to several components at once using a single toggle switch

I am looking to implement a day/night feature on my web app, triggered by a simple toggle click. While I can easily add this feature to a single component using the navigation menu, I am faced with the challenge of incorporating it into multiple component ...

A step-by-step guide to setting up Firebase Cloud Messaging in Angular 2

Looking to set up Firebase Cloud Messaging in Angular2 / TypeScript / AngularFire2? You can find detailed instructions for configuring it with JavaScript at this link: https://firebase.google.com/docs/cloud-messaging/js/client ...

Using TypeScript 4.1, React, and Material-UI, the className attribute does not support the CSSProperties type

Just starting out with Material-UI and we're utilizing the withStyles feature to style our components. Following the guidelines laid out here, I successfully created a classes object with the appropriate types. const classes = createStyles({ main ...

Button in Angular CLI not triggering method on click event

After running the phpStorm Angular CLI project, I encountered an issue with adding a button and assigning a listener to it for the click event. Despite researching extensively and even referencing code from the official Angular documentation, the button do ...

Animating progress bars using React Native

I've been working on implementing a progress bar for my react-native project that can be used in multiple instances. Here's the code I currently have: The progress bar tsx: import React, { useEffect } from 'react' import { Animated, St ...

Leveraging Angular2's observable stream in combination with *ngFor

Below is the code snippet I am working with: objs = [] getObjs() { let counter = 0 this.myService.getObjs() .map((obj) => { counter = counter > 5 ? 0 : counter; obj.col = counter; counter++; return view ...

Encountering issues passing the --aot and --prod flags to the ng build command

I'm having trouble passing flags to ng build. Here is the line of code I have: "build:aot:prod": "node --max_old_space_size=8092 ./node_modules/@angular/cli/bin/ng build --aot --prod" However, it seems to only run ng build without the flags. What co ...

Exploring the Possibility of Retrieving and Showing a PDF File from a Server in Angular 2 RC 5

I am currently working on integrating a PDF generated by a server into a view within my Angular 2 RC 5 project. The ASPNETCORE server is transmitting the object as an 'application/pdf', while the Angular client is attempting to interpret the resp ...

Create a new instance of the TypeScript singleton for each unit test

I have a TypeScript singleton class structured like this: export default class MySingleton { private constructor({ prop1, prop2, ... }: MySingletonConfig) { this.prop1 = prop1 ?? 'defaultProp1'; this.prop2 = prop2; ...

The absence of a template or render function in a Vue.js 3 and Quasar 2 component has resulted in an

I am currently working on creating a dynamic component and passing a prop to it. However, I am encountering a warning message that says: Component is missing template or render function. Although the component is being rendered, I am still receiving the wa ...

An issue arose during the installation of the package 'npm i angularfire2'

I am currently working on an Angular project and I am trying to import AngularFireStorage using the following line of code: import { AngularFireStorage } from 'angularfire2/storage'; I attempted to do this by running the command npm i angularfire ...

Convert Angular 2 Observable to a regular value

Currently using version 6.3 of NGX Data Table, I am facing an issue where I cannot bind to an observable collection. How can I convert an Angular Observable Collection into a standard non-observable Array? Below is the code snippet for the service: priva ...

I encountered an issue in my project where the TypeScript compiler failed to throw an error despite expecting

I'm currently facing an issue with one of my projects where the TypeScript compiler is not flagging a type mismatch that I would normally expect it to catch. Interestingly, when I run the same code block in the TypeScript playground, it does throw an ...

Converting a .ts file to .js for Typescript 3.2 and higher versions

Is there an alternative method to compile a .ts file to .js file using Typescript version 3.2 and above since tsc.exe is no longer present in these versions? In our project, we relied on tsc.exe to compile all the .ts files, but with the upgrade to Typesc ...

Troubleshooting the issue of Angular 2 error: Cannot access the 'getOptional' property

Currently, I am navigating my way through angular 2 and attempting to define a service named searchservice. I want to inject this service in the bootstap part of my project: import {SearchService} from 'src/service'; Here is the code for the Se ...

Utilize Polymer 3 component to import object values

In one of my polymer 3 components, I have declared an object property as follows: static get properties(): myInferface { return { myObject: { type: Object, notify: true, value: { showMe: false, text: ...