chedli chris
chedli chris

Reputation: 23

Angular 8, get current user in authentification service

What I get from the the backend api

I'm trying to get the current user as an observable in authentication service, so I can display the user name in any component that subscribes to the authService.

Everything works fine, but I can't get the current user.

Authentication service:

import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http'
import { Router } from '@angular/router'
import { User } from '../models/user'
import { Observable, BehaviorSubject } from 'rxjs';
import { map } from 'rxjs/operators';

@Injectable({
  providedIn: 'root'
})
export class AuthentificationService {
  private _registerUrl = "http://localhost:3000/api/users/register"
  private _loginUrl = "http://localhost:3000/api/users/login"
  private currentUserSubject: BehaviorSubject<any>;

  public currentUser: Observable<any>;

  constructor(private http: HttpClient, private router: Router) {}

  register(user): Observable<any> {
    return this.http.post<any>(this._registerUrl, user)
  }

  login(user): Observable<any> {
    return this.http.post<any>(this._loginUrl, user)
      .pipe(map(userInfo => {
        localStorage.setItem('token', userInfo.token)
        this.currentUser = userInfo.user
        return userInfo.user
      }))
  }

  public getCurrentUser(): Observable<any> {
    return this.currentUser;
  }

onSubmit method of login component:

onSubmit() {
    const infoUser = {
      email: this.email,
      password: this.password
    }

    //reset alert on submit
    // this.alertServ.clear()

    this.authService.login(infoUser).pipe(first()).subscribe(loggingData => {
      this.router.navigate(['/'])
    },
      err => {
        this.errors = err.error
        this.errorMessage = "verify email or password"
        this.alertServ.error(this.errorMessage)
      }
    )
  }
}

modified login method :

login(user): Observable<any> {

    return this.http.post<any>(this._loginUrl, user)
      .pipe(map(userInfo => {



        localStorage.setItem('token', userInfo.token)

        console.log(userInfo)
        this.currentUserSubject.next(userInfo)
        return userInfo



      }))



  }

  public getCurrentUser(): Observable<any> {


    return this.currentUserSubject.asObservable()


Upvotes: 1

Views: 17622

Answers (1)

Daniel W Strimpel
Daniel W Strimpel

Reputation: 8470

You probably need to instantiate your user subject and pump the value into it using its next(..) method.

private currentUserSubject = new BehaviorSubject<any>(null); // initializing with no user object since logged out

...

login(user): Observable<any> {
  return this.http.post<any>(this._loginUrl, user).pipe(
    map(userInfo => {
      localStorage.setItem('token', userInfo.token);

      this.currentUserSubject.next(userInfo.user); // <-- pump the value in here

      return userInfo.user;
    })
  );
}

Finally, in your getCurrentUser() method you want to return the observable version of your subject:

getCurrentUser(): Observable<any> {
  return this.currentUserSubject.asObservable();
}

Upvotes: 3

Related Questions