1 import * as Cookies from 'js-cookie';
2 import { User, LoginResponse } from '../interfaces';
3 import * as jwt_decode from 'jwt-decode';
4 import { Subject } from 'rxjs';
6 export class UserService {
8 private static _instance: UserService;
10 public sub: Subject<{user: User, unreadCount: number}> = new Subject<{user: User, unreadCount: number}>();
12 private constructor() {
13 let jwt = Cookies.get("jwt");
17 console.log('No JWT cookie found.');
22 public login(res: LoginResponse) {
23 this.setUser(res.jwt);
24 Cookies.set("jwt", res.jwt);
25 console.log("jwt cookie set");
29 this.user = undefined;
30 Cookies.remove("jwt");
31 console.log("Logged out.");
32 this.sub.next({user: undefined, unreadCount: 0});
35 public get auth(): string {
36 return Cookies.get("jwt");
39 private setUser(jwt: string) {
40 this.user = jwt_decode(jwt);
41 this.sub.next({user: this.user, unreadCount: 0});
42 console.log(this.user);
45 public static get Instance(){
46 return this._instance || (this._instance = new this());