5

I have to get current user ID to use it in different parts in my app..

login.component.ts:

onSignin(form: NgForm){
const UserName = form.value.UserName;
const Password = form.value.Password;
this.authService.signinUser(UserName,Password).map(res => res.json())
 .subscribe(
   data => {
     if (data.Id == 0){
     this.invalid=true;
    }
    else{
      localStorage.setItem('isLoggedin', 'true');
      this.router.navigate(['/calendar']);
      console.log('Ok');
   }})}

auth.service.ts:

signinUser(UserName,Password): Observable<any>{
  return this.http.get('http://api.##.com/api/security/signin?username='+UserName+'&password='+Password);
}
Aya Abdelaziz
  • 355
  • 3
  • 10
  • 23

2 Answers2

5

You want to use the userID you get from the Service call to different components in you app. I hope this is what you are looking for.

There are three ways you can do this .

  1. Shared Services - Make use of a shared service add the userID to a user id subject in the service and set this up at the time of login in . The next time when the user Id is changed the observing component will be notified.
  2. NGRX - A much cleaner implementation of shared service , i would suggest you to use this if your app is huge.
  3. Local storage - this is very debatable as it depends on users discretion too . Set and get User id between components.

Do note that if the user hard refreshes the page any time in NGRX or Shared services the data will be lost you might need to use local storage for full proofing.

Rahul Singh
  • 19,030
  • 11
  • 64
  • 86
  • Can you please look into this: https://stackoverflow.com/questions/63539252/how-to-fetch-data-from-localstorage-of-a-browser-synchronously-in-angular/63539278?noredirect=1#comment112356502_63539278 – Tanzeel Aug 27 '20 at 04:46
4

You can pass the token from the backend which will contain the id or you can use redux store which will store the id on the front end for your application to use. Below is the link for ng2 Redux package in angular. https://www.npmjs.com/package/ng2-redux There is also an option to save it into local storage but I will not prefer it.Or You can use session storage to save the data on the front end like this

saving in the session in your login Component file use this code

sessionStorage.setItem('id', data.id);
retrieving from the session//
var data = sessionStorage.getItem('id');
console.log(data) to see the id in the console
Abhishek Singh
  • 900
  • 7
  • 19