Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get current user id angular 4?

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);
}
like image 270
Aya Abdelaziz Avatar asked Oct 03 '17 12:10

Aya Abdelaziz


2 Answers

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.

like image 105
Rahul Singh Avatar answered Oct 17 '22 08:10

Rahul Singh


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
like image 4
Abhishek Singh Avatar answered Oct 17 '22 10:10

Abhishek Singh