вышел из системы во время обновления страницы - PullRequest
0 голосов
/ 10 апреля 2020

Потратил 2 дня, глядя на то, почему хранилище сеанса становится нулевым, когда я перезагружаю страницу, у меня потерян токен и текущий пользователь, даже когда я устанавливаю uri в / logint, когда сеанс вышел из системы, Потратил много времени на поиск в Google, нет Идея, что делать ...

Вот как UserService:

..
export class UserService {

    private currentUserSubject: BehaviorSubject<JwtResponse>;
    public currentUser: Observable<JwtResponse>;
    public nameTerms = new Subject<string>();
    public name$ = this.nameTerms.asObservable();
    constructor(private http: HttpClient,
    private cookieService: CookieService) 
    {
        const memo = localStorage.getItem('currentUser');
        this.currentUserSubject = new BehaviorSubject<JwtResponse>(JSON.parse(memo));
        this.currentUser = this.currentUserSubject.asObservable();
        cookieService.set('currentUser', memo);
    }

    get currentUserValue() {
        return this.currentUserSubject.value;
    }

    login(loginForm): Observable<JwtResponse> {

        const url = `${apiUrl}/login`;
        return this.http.post<JwtResponse>(url, loginForm).pipe(
            tap(user => {
                if (user && user.token) {

                    this.cookieService.set('currentUser', JSON.stringify(user));

                    if (loginForm.remembered) {
                        localStorage.setItem('currentUser', JSON.stringify(user));
                    }        

                    this.nameTerms.next(user.name);
                    this.currentUserSubject.next(user);
                    return user;
                }
            }),
           ...............
        );
    }

А вот и сам auth-guard:

export class AuthGuard implements CanActivate {


    constructor(
        private router: Router,
        private userService: UserService
    ) {
    }

    canActivate(
        route: ActivatedRouteSnapshot,
        state: RouterStateSnapshot): Observable<boolean> | Promise<boolean> | boolean {
        const currentUser = this.userService.currentUserValue;
        if (currentUser) {
            // check if route is restricted by role
            if (route.data.roles && route.data.roles.indexOf(currentUser.role) === -1) {
                console.log(currentUser.role + "fail in " + route.data.roles);
                // role not authorised so redirect to home page
                this.router.navigate(['/']);
                return false;
            }
            // authorised so return true
            return true;
        }

        console.log("Need log in");
        // not logged in so redirect to login page with the return url{queryParams: {returnUrl: state.url}}
        this.router.navigate(['/login'], {queryParams: {returnUrl: state.url}});
        return false;
    }
}

это мой app.compon enet

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title = 'shop';
}

1 Ответ

1 голос
/ 10 апреля 2020

проверьте, как работает sessionStorage и localStorage, вот статья об этом:

https://alligator.io/js/introduction-localstorage-sessionstorage/

Нам нужно посмотреть, как работает ваш cookieService, и проверить в какой части своего кода вы проверяете сеанс, если он находится в компоненте приложения, или в качестве первого компонента в качестве целевого

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...