userService now persist user data in localStorage
This commit is contained in:
parent
a12b30998d
commit
df20d25a35
2 changed files with 11 additions and 8 deletions
|
|
@ -1,6 +1,6 @@
|
||||||
import { HttpClient } from '@angular/common/http';
|
import { HttpClient } from '@angular/common/http';
|
||||||
import { Injectable } from '@angular/core';
|
import { Injectable } from '@angular/core';
|
||||||
import { BehaviorSubject, Observable, distinctUntilChanged, tap } from 'rxjs';
|
import { Observable, tap } from 'rxjs';
|
||||||
import { Recipe, Recipe01 } from '../models/recipe.model';
|
import { Recipe, Recipe01 } from '../models/recipe.model';
|
||||||
import { environment } from 'src/environments/environment';
|
import { environment } from 'src/environments/environment';
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -19,17 +19,18 @@ export class UserService {
|
||||||
.asObservable()
|
.asObservable()
|
||||||
.pipe(distinctUntilChanged());
|
.pipe(distinctUntilChanged());
|
||||||
|
|
||||||
public isAuthenticated = this.currentUser.pipe(
|
public isAuthenticated = this.currentUser.pipe(map((user) => !!user));
|
||||||
map((user) => !!user),
|
|
||||||
tap((isAuth) => {
|
|
||||||
console.log('Change auth', isAuth);
|
|
||||||
})
|
|
||||||
);
|
|
||||||
|
|
||||||
constructor(
|
constructor(
|
||||||
private readonly http: HttpClient,
|
private readonly http: HttpClient,
|
||||||
private readonly router: Router
|
private readonly router: Router
|
||||||
) {}
|
) {
|
||||||
|
const user = localStorage.getItem('user');
|
||||||
|
|
||||||
|
if (user) {
|
||||||
|
this.currentUserSubject.next(JSON.parse(user));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
logout(): void {
|
logout(): void {
|
||||||
this.purgeAuth();
|
this.purgeAuth();
|
||||||
|
|
@ -59,10 +60,12 @@ export class UserService {
|
||||||
}
|
}
|
||||||
|
|
||||||
setAuth(user: User): void {
|
setAuth(user: User): void {
|
||||||
|
window.localStorage.setItem('user', JSON.stringify(user));
|
||||||
void this.currentUserSubject.next(user);
|
void this.currentUserSubject.next(user);
|
||||||
}
|
}
|
||||||
|
|
||||||
purgeAuth(): void {
|
purgeAuth(): void {
|
||||||
|
window.localStorage.removeItem('user');
|
||||||
void this.currentUserSubject.next(null);
|
void this.currentUserSubject.next(null);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
||||||
Loading…
Add table
Add a link
Reference in a new issue