import {Injectable} from '@angular/core'; import {HttpClient, HttpHeaders} from '@angular/common/http'; import {Observable} from 'rxjs/internal/Observable'; import {catchError, tap} from 'rxjs/operators'; import {Subject} from 'rxjs/internal/Subject'; import {ErrorLoggerService} from '../core/error-logger.service'; import {User} from '../user/user'; const httpOptions = { headers: new HttpHeaders({'Content-Type': 'application/json'}) }; const loginUrl = '/api/login'; const logoutUrl = '/api/logout'; const checkUrl = '/api/Auth'; @Injectable({ providedIn: 'root' }) export class AuthService { public userObservable = new Subject(); constructor(private http: HttpClient, private log: ErrorLoggerService) { this.check().subscribe(); } private _user: User; get user() { return this._user; } set user(user: User) { this._user = user; this.userObservable.next(user); } login(name: string, password: string, otp?: string, clientName?: string): Observable { const data = {name: name, password: password}; if (otp) { data['otp'] = otp; } if (clientName) { data['clientName'] = clientName; } return this.http.post(loginUrl, data, httpOptions) .pipe( tap((user: User) => this.user = user), catchError(this.log.handleError('AuthService', 'login')) ); } logout(): Observable { return this.http.post(logoutUrl, {}, httpOptions) .pipe( tap((user: User) => this.user = user), catchError(this.log.handleError('AuthService', 'logout')) ); } check(): Observable { return this.http.get(checkUrl, httpOptions) .pipe( tap((user: User) => this.user = user), catchError(this.log.handleError('AuthService', 'check')) ); } }