Home > Mobile >  Exporting ID from one component to another component in angular
Exporting ID from one component to another component in angular

Time:05-17

I'm working on piece of code in angular which is books management. I was hosting JSON data using this. When the user is logged in, I need to export 'id' instead of the mail from login component to wish-list component.

data.json

{
  "Users": [
    {
      "id": 1,
      "userName": "Deepak Sharma",
      "Password": "dep@123!",
      "Phone": "9988776655",
      "Email": "[email protected]",
      "UserType": "Customer",
      "WishList": [ 1, 2, 3 ],
      "Completed": [4, 5, 6 ]
    },
    {
      "username": "val1",
      "Password": "val1",
      "Phone": 123,
      "Email": "[email protected]",
      "WishList": [],
      "Completed": [],
      "id": 3
    }
  ]
}

login-page.component.ts

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


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

  public loginForm!: FormGroup;
  static emailId: any;
  static emailIdUserGave: any;
  constructor(private formBuilder : FormBuilder, private http: HttpClient, private router: Router) { }

  ngOnInit(): void {
    this.loginForm = this.formBuilder.group({
      Email: ['', Validators.required],
      Password: ['', Validators.required]
    })
  }

  login(){
    this.http.get<any>("http://localhost:3500/Users")
    .subscribe(res=>{
      const user = res.find((a:any) =>{
        return a.email === this.loginForm.value.email && a.password === this.loginForm.value.password
      });
      if (user) {
        alert("Login Success!");
        this.loginForm.reset();
        let emailIdUserGave = this.loginForm.value.email; 
        //Variable I want to export ifincase id dosen't export
        this.router.navigate(['user'])
      } else {
        alert("User Not found. Create account !!");
      }
    }, err=>{
      alert("Something Went Wrong");
    })
  }

}

From login-page.component.ts, I want to export the ID to this wish-list.component.ts

import { Component, OnInit, ViewChild } from '@angular/core';
import { LoginPageComponent } from '../login-page/login-page.component';

@Component({
  selector: 'app-wishlist-page',
  templateUrl: './wishlist-page.component.html',
  styleUrls: ['./wishlist-page.component.css']
})
export class WishlistPageComponent implements OnInit {
  
  constructor() { }

  ngOnInit(): void {
  }

}

CodePudding user response:

Looks like you need to make use of a service (which we would use as a singleton in this case).

Create a service using (called user.service.ts here but call what you like):

ng g s user

Move your login logic into a function in the service, and set a property on the service with the user object to be used later.

You can inject this service into both components using:

constructor(private userService: UserService) {}

You can call the login function then in your login component like:

this.userService.login(this.formGroup.value);

And directly access the user property that has been set on the service from your wishlist component.

There is good information about angular services in the docs, that would be beneficial to read: https://angular.io/guide/architecture-services

Good luck!

CodePudding user response:

My suggestion is to create an authentication service.

This service could store (in cookies or in session storage) a JWT token (as per my suggestion), but if you just want to do a simple process, store the Id.

From then on, the service should have the authenticate function and an isAuthenticated function.

isAuthenticated you look for the user data in the storage an in case it has nothing it could go for the backend using the authenticate function.

let me know if you have doubts on how to do it

  • Related