[993189e] | 1 | import { Injectable } from '@angular/core';
|
---|
| 2 | import { Router } from '@angular/router';
|
---|
| 3 | import { HttpClient, HttpErrorResponse } from '@angular/common/http';
|
---|
| 4 | import { BehaviorSubject, Observable } from 'rxjs';
|
---|
| 5 | import { catchError, map } from 'rxjs/operators';
|
---|
| 6 | import { IPharmacyHead } from './interfaces';
|
---|
| 7 | import { DataService } from './data.service';
|
---|
| 8 |
|
---|
| 9 |
|
---|
| 10 | @Injectable({
|
---|
| 11 | providedIn: 'root'
|
---|
| 12 | })
|
---|
| 13 | export class AuthService {
|
---|
| 14 | private headSubject: BehaviorSubject<IPharmacyHead>;
|
---|
| 15 | public head: Observable<IPharmacyHead>;
|
---|
| 16 | basePharmacyHead: string = '/api/pharmacyhead';
|
---|
| 17 |
|
---|
| 18 | constructor(private router: Router, private http: HttpClient, private dataService: DataService) {
|
---|
| 19 | this.headSubject = new BehaviorSubject<IPharmacyHead>(JSON.parse(localStorage.getItem('head')));
|
---|
| 20 | this.head = this.headSubject.asObservable();
|
---|
| 21 | }
|
---|
| 22 |
|
---|
| 23 | public get headValue(): IPharmacyHead {
|
---|
| 24 | return this.headSubject.value;
|
---|
| 25 | }
|
---|
| 26 |
|
---|
| 27 | login(email: string, passwd: string) : Observable<any> {
|
---|
| 28 | let postData = {email : email ,password : passwd};
|
---|
| 29 | return this.http.post<any>(this.basePharmacyHead + '/login', postData)
|
---|
| 30 | .pipe(
|
---|
| 31 | map((data) => {
|
---|
| 32 | localStorage.setItem('head', JSON.stringify(data));
|
---|
| 33 | this.headSubject.next(data);
|
---|
| 34 | return data;
|
---|
| 35 | }),
|
---|
| 36 | catchError(this.handleError)
|
---|
| 37 | );
|
---|
| 38 | }
|
---|
| 39 |
|
---|
| 40 | logout() {
|
---|
| 41 | localStorage.removeItem('user');
|
---|
| 42 | this.headSubject.next(null);
|
---|
| 43 | this.router.navigate(['/login']);
|
---|
| 44 | }
|
---|
| 45 |
|
---|
| 46 | private handleError(error: HttpErrorResponse) {
|
---|
| 47 | console.error('server error:', error);
|
---|
| 48 | if (error.error instanceof Error) {
|
---|
| 49 | let errMessage = error.error.message;
|
---|
| 50 | return Observable.throw(errMessage);
|
---|
| 51 | }
|
---|
| 52 | return Observable.throw(error || 'ASP.NET Core server error');
|
---|
| 53 | }
|
---|
| 54 | }
|
---|