// services
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { catchError, map, Observable } from 'rxjs';
import { ConfigurationService } from './configuration.service';
import { Presocloud } from 'src/app/interfaces/presucloud';
import { Router } from '@angular/router';
import { HeaderComponent } from '../shared/components/header/header.component';
import { BehaviorSubject, Observable } from "rxjs";
isLoginSubject = new BehaviorSubject<boolean>(this.hasToken());
const httpOptions = {
headers: new HttpHeaders({
'Content-Type': 'application/json',
'X-Requested-With': 'XMLHttpRequest',
Accept: '*/*',
}),
};
@Injectable({
providedIn: 'root',
})
export class AuthenticationService {
private URL_BASE: string;
constructor(
private configuration: ConfigurationService,
private http: HttpClient,
private router: Router,
) {
this.URL_BASE = this.configuration.getUrlBase();
}
httpOptions = {
headers: new HttpHeaders({
'Content-Type': 'application/json',
}),
};
private hasToken() : boolean {
return !!localStorage.getItem('token');
}
singup(data: any) {
return this.http.post(this.URL_BASE + 'signup', data);
}
login(email: string, password: string): Observable<Presocloud> {
const user: any = {
email: email,
password: password,
};
return this.http
.post<Presocloud>(
this.URL_BASE + 'login',
JSON.stringify(user),
this.httpOptions
)
.pipe(
map((res: any) => {
this.authSuccess(res.access_token);
return res;
})
);
}
isLoggedIn() : Observable<boolean> {
return this.isLoginSubject.asObservable();
}
authSuccess(token: string) {
localStorage.setItem('token', token);
this.isLoginSubject.next(true);
}
getToken(): string | null {
return localStorage.getItem("token");
}
logout() {
localStorage.removeItem("token");
this.isLoginSubject.next(false);
this.router.navigate(["login"]);
}
}
//header
import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';
import { AuthenticationService } from 'src/app/services/authentication.service';
import { Observable } from "rxjs";
@Component({
selector: 'app-header',
templateUrl: './header.component.html',
styleUrls: ['./header.component.css'],
})
export class HeaderComponent implements OnInit {
isLoggedIn : Observable<boolean>;
constructor(
private authenthication: AuthenticationService,
private router: Router
) { this.isLoggedIn = authService.isLoggedIn();}
ngOnInit(): void {}
verifyLooged() {
this.isLoggedInO.subscribe(bole=>{if(bole ==true) this.router.navigateByUrl('home'); })