mrkibzk
mrkibzk

Reputation: 227

Angular 6 problem with checking localstorage on app init

I have problem with checking on page load if user is logged in app or no. I tried with eventEmmiter and Subject but on load there is not result for checking in local storage.

This is my AuthenticationService

export class AuthenticationService {
  constructor() {
  }
  // here is bunch of code

  isLoggedIn(): boolean {
    let currentUser = localStorage.getItem('currentUser');
    return !!(currentUser);
  }

}

and this is my HedaerComponent:

constructor(private authenticationService: AuthenticationService) {
 this.checkUser();
}

checkUser() {
 if (this.authenticationService.isLoggedIn()) {
 // do something
 }
 else {
 // do something
 }
}

I have problem with first loading of app, how can I check if user i logged or not? As I sad I try with emmiting value but with no results. Thanks for help!

Upvotes: 1

Views: 922

Answers (3)

mrkibzk
mrkibzk

Reputation: 227

I solved my problem with adding new service, here is example

import { Subject } from 'rxjs';

class CustomEventEmitter extends Subject<any>{
 constructor() {
    super();
 }
 emit(value: any) {
    super.next(value);
 }
}

export class PubSubService {
 Stream: CustomEventEmitter;
 constructor() {
    this.Stream = new CustomEventEmitter;
 }
}

Thanks for help!

Upvotes: 0

Wei-jye
Wei-jye

Reputation: 442

You can use Angular's route guard to achieve that. Here's some tutorial:

  1. https://ryanchenkie.com/angular-authentication-using-route-guards

  2. https://angular.io/guide/router#milestone-5-route-guards

Upvotes: 1

Nagendra Pantham
Nagendra Pantham

Reputation: 59

It should help

 let currentUser = JSON.parse(localStorage.getItem('currentUser'));

Upvotes: 0

Related Questions