'How do I use the values from the input fields to store them into a variable so I can build Authentication and how do I call the JSON data?

I am fairly new to Angular and have been having issues regarding how to store the data from the input field into a variable and then use the data to authenticate the user from my JSON file. Any sort of help will be appreciated.

The first issue for me is to store the values from the input fields into a variable. And is it possible for me to use those variables to authenticate the user using my JSON data?

<div fxLayoutAlign="center center" fxFlexFill>
    <mat-card fxFlex="35">
        <form formGroup="LoginForm" fxLayoutAlign="stretch" fxLayout="column" (ngSubmit)="Submit()">
            <mat-form-field appearance="outline">
              <input matInput type="text" id="uname" placeholder="Username" required>
            </mat-form-field>
            <mat-form-field appearance="outline">
                <input matInput type="password" id="pswd" placeholder="Password" required>
            </mat-form-field>
            <button mat-raised-button type="submit" color="primary" routerLink = '/commonPage'>Log in</button>
            <br>
            <button mat-raised-button type="button" color="primary" routerLink = '/registerPage'>Register</button>
        </form>
    </mat-card>
</div>

import { Component } from '@angular/core';
import { FormControl } from '@angular/forms';
import { HttpClient } from '@angular/common/http';
import jsondata from '../data.json';

interface jsonData{
  id: Number,
  firstName: String,
  lastName: String,
  userName: String,
  password: String,
}

@Component({
  selector: 'app-login',
  templateUrl: './login.component.html',
  styleUrls: ['./login.component.css']
})
export class LoginComponent {
  Jsondata: jsonData[] = jsondata;

  emailControl = new FormControl('');
  passwordControl = new FormControl('');

  constructor(private http: HttpClient){

  }

  Submit(){
    console.log('values stored');
  }

}


[
    {
        "id": 1,
        "firstName": "John",
        "lastName": "Myers",
        "userName": "[email protected]",
        "password": "johnmyers123"
    },
    {
        "id": 2,
        "firstName": "Chris",
        "lastName": "Evans",
        "userName": "[email protected]",
        "password": "chrisevans123"
    },
    {
        "id": 3,
        "firstName": "Robert",
        "lastName": "Downey",
        "userName": "[email protected]",
        "password": "robertdowney123"
    },
    {
        "id": 4,
        "firstName": "Kevin",
        "lastName": "Hart",
        "userName": "[email protected]",
        "password": "kevinhart123"
    },
    {
        "id": 5,
        "firstName": "Leo",
        "lastName": "Messi",
        "userName": "[email protected]",
        "password": "leomessi123"
    }
]


Solution 1:[1]

You should have a LoginForm: FormGroup field in your component.ts and initialize it with your emailControl and passwordControl

In your <form> you should include square brackets around your formGroup like this: <form [formGroup]="LoginForm" to properly bind your FormGroup field with the DOM.

Your <input> should also include formControlName for the same reason.

user:

<input formControlName="emailControl" matInput type="text" id="uname" placeholder="Username" required>

email:

<input formControlName="passwordControl" matInput type="password" id="pswd" placeholder="Password" required>

Now in your Submit() function you should have access to the inputs.

component code


import { Component } from '@angular/core';
import { FormControl } from '@angular/forms';
import { HttpClient } from '@angular/common/http';

interface jsonData{
  id: Number,
  firstName: String,
  lastName: String,
  userName: String,
  password: String,
}

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

  LoginForm: FormGroup = new FormGroup({
    emailControl: new FormControl(''),
    passwordControl: new FormControl('')
  };

  constructor(private http: HttpClient){

  }

  Submit(){
    this.http.get<jsonData[]>('./../data.json')
       .subscribe(data => {
         console.log(data); // you should now have your json array here 

         // check our form against the data.
         let email = this.LoginForm.controls.emailControl.value;
         let password = this.LoginForm.controls.passwordControl.value;

         let isValid = false;
         for (let account of data) {
            if (account.userName === email && account.password === password) {
              console.log('do whatever now');
              isValid = true;
              break;
            }
         }
         
         if (!isValid) {
            console.log('not valid');
         }
       });
  }

}

Something like that should work. However, now that you authenticated a user (verified them), I assume you want to setup authorization, guard routes, etc. This looks like a small demo learning app so I would suggest reading up on Route Guards, authorization (basic auth, JWT)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 user1738539