0

I need to get my user informations. I use this code to do it :

export class AuthService {
.
.
.
  private currentUser: Collaborator;

  getCurrentUser() {
    return this.currentUser;
  }

  login(user: Login) {
    this.http.post(this.signInUrl, user).subscribe((data: JwtToken) => {
      this.setToken(data.tokenType + ' ' + data.accessToken);
      this.collabService.getCurrentUser().subscribe((data: Collaborator) => {
        this.currentUser = data;
      });
    });
  }
}

But when I use my 'currentUser' var with getter in other component, the value is "undefined".

export class HeaderComponent implements OnInit {
.
.
.
  public currentUser: Collaborator;

  ngOnInit() {
    this.currentUser = this.authService.getCurrentUser(); --> is undefined
  }
}

How I can save the value response in var to use it everywhere ?

  • 3
    Where and how are you calling `login`? – Keff Dec 24 '19 at 15:02
  • Does this answer your question? [How to return value from function which has Observable subscription inside?](https://stackoverflow.com/questions/38291783/how-to-return-value-from-function-which-has-observable-subscription-inside) – Reactgular Dec 24 '19 at 15:14

1 Answers1

1

Change your Auth Service according to this: -

export class AuthService {
  public currentUser:any;


  getCurrentUser() {
    return this.currentUser;
  }

  setCurrentUser(user) {
     this.currentUser=user;
  }

  login(user: Login) {
    this.http.post(this.signInUrl, user).map((res: Response) => {
    return res.json();
    });
  }
  getColabUser(){
    this.collabService.getCurrentUser().map((res: Response) => {
    return res.json();
    });
  }

}

Change your HeaderComponent.ts file :-

export class HeaderComponent implements OnInit {

      public currentUser: Collaborator;

      ngOnInit() {
         this.authService.login(user).subscribe((data)=>{
           this.setToken(data.tokenType + ' ' + data.accessToken); // Either use seperate method in the service file to store token details
             this.collabService.getCurrentUser().subscribe((user) => {
                 this.authService.setCurrentUser(data);
                 this.currentUser = this.authService.getCurrentUser();
          });
         });
      }
    }

Now you can get the current user details stored in the AuthService whenever you need via the getCurrentUser() method.

Selaka Nanayakkara
  • 3,296
  • 1
  • 22
  • 42