From 110f2ab8d7bf5cf5fefee2fadb89f0e548dc0f4d Mon Sep 17 00:00:00 2001 From: crupest Date: Mon, 18 Mar 2019 21:21:56 +0800 Subject: Add logout. Fix a bug. The bug is it always goes to login page whether you have login or not before when user is presented in url. --- .../internal-user-service/internal-user.service.ts | 23 +++++++++++++++------- 1 file changed, 16 insertions(+), 7 deletions(-) (limited to 'Timeline/ClientApp/src/app/user/internal-user-service') diff --git a/Timeline/ClientApp/src/app/user/internal-user-service/internal-user.service.ts b/Timeline/ClientApp/src/app/user/internal-user-service/internal-user.service.ts index 2098391e..d82e9613 100644 --- a/Timeline/ClientApp/src/app/user/internal-user-service/internal-user.service.ts +++ b/Timeline/ClientApp/src/app/user/internal-user-service/internal-user.service.ts @@ -3,7 +3,7 @@ import { HttpClient, HttpErrorResponse } from '@angular/common/http'; import { Router } from '@angular/router'; import { Observable, throwError, BehaviorSubject, of } from 'rxjs'; -import { map, catchError, retry, switchMap, tap } from 'rxjs/operators'; +import { map, catchError, retry, switchMap, tap, filter } from 'rxjs/operators'; import { AlreadyLoginError, BadCredentialsError, BadNetworkError, UnknownError } from './errors'; import { @@ -35,14 +35,13 @@ export const TOKEN_STORAGE_KEY = 'token'; export class InternalUserService { private token: string | null = null; - private userInfoSubject = new BehaviorSubject(null); + private userInfoSubject = new BehaviorSubject(undefined); - get currentUserInfo(): UserInfo | null { - return this.userInfoSubject.value; - } + readonly userInfo$: Observable = + >this.userInfoSubject.pipe(filter(value => value !== undefined)); - get userInfo$(): Observable { - return this.userInfoSubject; + get currentUserInfo(): UserInfo | null | undefined { + return this.userInfoSubject.value; } private openSnackBar(snackBar: MatSnackBar, textKey: SnackBarTextKey) { @@ -129,4 +128,14 @@ export class InternalUserService { }) ); } + + logout() { + if (this.currentUserInfo === null) { + throw new Error('No login now. You can\'t logout.'); + } + + this.window.localStorage.removeItem(TOKEN_STORAGE_KEY); + this.token = null; + this.userInfoSubject.next(null); + } } -- cgit v1.2.3