Search code examples
angulartypescriptuserid

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);
}

Solution

  • 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