Genger
Genger

Reputation: 95

how I get the name of current user logged in angular 4?

My Angular4 application should get the current logged in user How can I get the user name in to my app.

 Signin(email: string, password:string ): Observable<boolean> {
    
   // console.log(info);
    var data = JSON.stringify({email: email, password: password});
    return this.http.post(this.server +"user/signin" , data, this.options).map((response: Response) => {
      // login successful if there's a jwt token in the response
      let token = response.json() && response.json().token;
      if (token) {
          // set token property
          this.token = token;

          // store username and jwt token in local storage to keep user logged in between page refreshes
          localStorage.setItem('currentUser', JSON.stringify({ email:email , token: token }));

          // return true to indicate successful login
          return true;
      } else {
          // return false to indicate failed login
          return false;
      }
  });
    }
in the login component.ts

  onSignin() {
    this.loading = true;
    this.authService.Signin(this.model.email, this.model.password)
        .subscribe(result => {
            if (result === true) {
                // login successful
                this.router.navigate(['/']);
            } else {
                // login failed
                this.error = 'Username or password is incorrect';
                this.loading = false;
            }
            
        });

Upvotes: 3

Views: 20929

Answers (1)

Sunny Gohil
Sunny Gohil

Reputation: 319

Looks like you are storing in the user email (which i assume is your username) in localstorage under currentUser.

So to get that email you would do the following in whatever component or service you require to get the information.

To do it via a service:

getUsername() {
    return JSON.parse(localStorage.getItem('currentUser')).email;
}

To get it directly in a component:

username = JSON.parse(localStorage.getItem('currentUser')).email;

// or if you are using the service method above then in your component do following:

username = this.myService.getUsername();

And thats it.

Upvotes: 5

Related Questions