import { HttpClient } from '@angular/common/http' ; import { Injectable } from '@angular/core' ; import { ISignUpDto , SignedUser } from '@api-interface' ; import { BehaviorSubject , Observable } from 'rxjs' ; import { map } from 'rxjs/operators' ; @ Injectable ( ) export class AuthenticationService { private currentUserSubject : BehaviorSubject < SignedUser > ; public currentUser : Observable < SignedUser > ; private apiUrl = 'http://localhost:3000' ; constructor ( private http ) { this . currentUserSubject = new BehaviorSubject < SignedUser > ( JSON . parse ( localStorage . getItem ( 'currentUser' ) ) ) ; this . currentUser = this . currentUserSubject . asObservable ( ) ; } public get currentUserValue ( ) : SignedUser { return this . currentUserSubject . value ; } login ( username , password ) { return this . http . post < SignedUser > ( `${ this . apiUrl }/auth/sign-in` , { username , password } ) . pipe ( map ( ( user ) => { if ( user && user . token ) { localStorage . setItem ( 'currentUser' , JSON . stringify ( { ... user , username } ) ) ; this . currentUserSubject . next ( user ) ; } return user ; } ) ) ; } register ( user ) { return this . http . post ( `${ this . apiUrl }/auth/sign-up` , user ) ; } logout ( ) { localStorage . removeItem ( 'currentUser' ) ; this . currentUserSubject . next ( null ) ; } }