SHARE
TWEET

Untitled

a guest Sep 22nd, 2019 96 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. import { Injectable } from '@angular/core';
  2. import { HttpClient } from '@angular/common/http';
  3. import { BehaviorSubject, Observable } from 'rxjs';
  4. import { map } from 'rxjs/operators';
  5. import { SERVER_API_URL } from 'app/app.constants';
  6.  
  7. @Injectable({ providedIn: 'root' })
  8. export class AuthenticationService {
  9.   private currentUserSubject: BehaviorSubject<any>;
  10.   public currentUser: Observable<any>;
  11.  
  12.   constructor(private http: HttpClient) {
  13.     this.currentUserSubject = new BehaviorSubject<any>(JSON.parse(sessionStorage.getItem('currentUser')));
  14.     this.currentUser = this.currentUserSubject.asObservable();
  15.   }
  16.  
  17.   public get currentUserValue() {
  18.     return this.currentUserSubject.value;
  19.   }
  20.  
  21.   login(email, password) {
  22.     return this.http.post<any>(SERVER_API_URL + '/api/authenticate', { email, password }).pipe(
  23.       map(user => {
  24.         // store user details and jwt token in local storage to keep user logged in between page refreshes
  25.         sessionStorage.setItem('currentUser', JSON.stringify(user));
  26.         this.currentUserSubject.next(user);
  27.         return user;
  28.       })
  29.     );
  30.   }
  31.  
  32.   logout() {
  33.     // remove user from local storage and set current user to null
  34.     sessionStorage.removeItem('currentUser');
  35.     this.currentUserSubject.next(null);
  36.   }
  37. }
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top