Home > database >  How to pass data from Student Login Component to Student Dashboard Component in Angular?
How to pass data from Student Login Component to Student Dashboard Component in Angular?

Time:05-04

student-login.component.ts --> I am storing the logged in user details in this component

import { HttpClient } from '@angular/common/http';
import { Component, OnInit, ViewChild, AfterViewInit } from '@angular/core';
import { FormGroup, FormBuilder, Validators } from '@angular/forms';
import { Router } from '@angular/router';


@Component({
  selector: 'app-student-login',
  templateUrl: './student-login.component.html',
  styleUrls: ['./student-login.component.css'],
})
export class StudentLoginComponent implements OnInit {
  public loginForm!: FormGroup;
  constructor(
    private formBuilder: FormBuilder,
    private http: HttpClient,
    private router: Router
  ) {}

  ngOnInit(): void {
    this.loginForm = this.formBuilder.group({
      rollNo: ['', Validators.required],
      name: ['', Validators.required],
    });
  }


  login() {
    this.http.get<any>('http://localhost:3000/posts').subscribe(
      (res) => {
        const user = res.find((u: any) => { //  I want to display this user in studentDashboardComponent
          return (
            u.id === this.loginForm.value.rollNo &&
            u.name === this.loginForm.value.name
          );
        });
        if (user) {
          alert('Login Successfull!!');
          localStorage.setItem('role', 'student');
          localStorage.setItem('studentId', user.id.toString());
          this.loginForm.reset();
          this.router.navigate(['studentDashboard']);
        } else {
          alert('Invalid credentials, please try again');
        }
      },
      (err) => {
        alert('Something went wrong');
      }
    );
  }
}

student-login.component.html

   <div >
      <div >
        <div >
          <div >
            <div >
              <h1>Student Login</h1>
            </div>
            <form [formGroup]="loginForm" (ngSubmit)="login()">
              <div >
                <label for="rollNo" >Roll No</label>
                <input
                  formControlName="rollNo"
                  type="number"
                  
                  id="rollNo"
                  aria-describedby="emailHelp"
                />
                <span
                  
                  *ngIf="
                    loginForm.controls['rollNo'].dirty &&
                    loginForm.hasError('required', 'rollNo')
                  "
                  >Roll No. is Required</span
                >
              </div>
              <div >
                <label for="name" >Name</label>
                <input
                  formControlName="name"
                  type="text"
                  
                  id="name"
                />
                <span
                  
                  *ngIf="
                    loginForm.controls['name'].dirty &&
                    loginForm.hasError('required', 'name')
                  "
                  >Name is Required</span
                >
              </div>
    
              <button
                [disabled]="!loginForm.valid"
                type="submit"
                
              >
                Login
              </button>
            </form>
            <a style="margin-top: 10px; color: #333333" routerLink="/home"
              >Back to Home</a
            >
          </div>
        </div>
      </div>
    </div>

db.json --> This is where I am storing studentDetails

To get records from db.json : http://localhost:3000/posts

To get a particular record: http://localhost:3000/posts/id

{
  "posts": [
    {
      "id": 2,
      "rollNo": 2,
      "name": "Bryan Percy",
      "dob": "2001-10-17",
      "score": 98
    },
    {
      "id": 3,
      "rollNo": 3,
      "name": "Robson",
      "dob": "1993-03-17",
      "score": 98
    },
    {
      "id": 4,
      "rollNo": "4",
      "name": "Bravo Espurisito",
      "dob": "2011-12-17",
      "score": 92
    }
  ]
}

student-dashboard.component.ts -> How do I get the logged in student user data in this component?

import { Component, Input, OnInit } from '@angular/core';
import { HttpClient } from '@angular/common/http';

@Component({
  selector: 'app-student-dashboard',
  templateUrl: './student-dashboard.component.html',
  styleUrls: ['./student-dashboard.component.css'],
})
export class StudentDashboardComponent implements OnInit {
  constructor(private http: HttpClient) {}
  ngOnInit(): void {}
}

student-dashboard.component.html -> I want to display the data of the logged in Student here

<h1>Student Dashboard</h1>



<!-- Display Student Data here -->
<div>Display Student Roll No</div>
<div>Display Student Name</div>
<div>Display Student Date of Birth</div>
<div>Display Student Score</div>

How do I get the details of the logged in student from the student-login component to the student-dashboard component?

CodePudding user response:

@viewChild("StudentLoginComponent",{static: true}), StudentLoginComponent: elementRef;

you can use view to access the complete dom of that

CodePudding user response:

Your question consist from 2 different things.

  1. Data sharing between 2 Components. Here you have at least 3 options:
  • Create a service, where you can set/get a data to/from unrelated components. For example:

     import { Injectable } from '@angular/core';
     import { BehaviorSubject } from 'rxjs';
    
     @Injectable({
      providedIn: 'root'
     })
     export class DataSharingService {
    
      private loginData = new BehaviorSubject<BasicLoginData>({userName:' '; userId: ' '});
    
    //you could create a getter and access this observable from any component  
    loginData$ = this.loginData.asObservable();
    
      constructor() {}
    
      // update with last login data  
      updateLoginData(loginData: BasicLoginData) {
      this.loginData.next(loginData)
      }
     }
    

your login-component - onSubmit-> UpdateLoginData

onSubmit() {
 this.dataSharinService.updateLoginData(
  userName: this.userName;
  id: this.userId
);
 }

your dashboard-component now, you can access the userName and id from here. But still -> you have to find the user with this ID

ngOnInit() {
     this.dataSharinService.loginData.subscribe(data => console.log(data));
     }
  1. The second part from the question would be how to find which user is logged.
  • If you have the ID of the logged user and since posts is array from objects you can .find() the user like:

    const loggedUser = posts.find(user => user.id = this.userId);

  • in the dashboard template you can just display it like:

    {{ loggedUser.rollNo }} {{ loggedUser.name }}

and so on..

  • Related