разделить переменную между компонентами angular - PullRequest
0 голосов
/ 12 марта 2020

Я пытаюсь разделить переменную между двумя независимыми компонентами.

Работает нормально, пока я не обновлю sh страницу, кнопка выхода из системы исчезнет. Я делю переменную с целью показать или скрыть эту кнопку (показывать ее, когда пользователь подключен)

Когда я использую ngAfterViewChecked, она работает, но я обнаружил, что это не очень хорошая практика.

login.service.ts

@Injectable({
  providedIn: 'root'
})
export class LoginService {
  private isLoggedIn = new Subject<boolean>();

  getIsLoggedIn(): Observable<boolean> {
    if (localStorage.getItem('token') != null) {
      this.updateIsLoggedIn(true);
      return this.isLoggedIn.asObservable();
    }else{

      return this.isLoggedIn.asObservable();
    }
 }

  updateIsLoggedIn(state: boolean) {
   this.isLoggedIn.next(state);
 }

Следующий метод выполняется, когда я нажимаю кнопку входа в систему

login.component.ts

login(AuthenticationRequest){
    this.loginService.login(AuthenticationRequest).subscribe(
      res => {
        console.log(res);
        localStorage.setItem('token',res.jwt);
        this.router.navigate(['patient/calendrier']);
        this.incorrect = false;
        this.loginService.updateIsLoggedIn(true);

      }, error => {
        console.log(error);
        this.incorrect = true;
      }
    )
  }

header.component. ts

export class HeaderComponent implements OnInit {

  subscription;
  isLoggedIn: boolean = false;

constructor(private router: Router, private loginService: LoginService) {

  }

  ngOnInit() {
    this.today = new Date();
    this.subscription = this.loginService.getIsLoggedIn().subscribe(
      state => { this.isLoggedIn = state;
      }
    )
  }


  logout() {
    console.log();
    localStorage.removeItem("token");
    this.loginService.updateIsLoggedIn(false);
    location.reload();

  }

  ngOnDestroy() {
    this.subscription.unsubscribe();
  }

header.component. html

...
<button *ngIf="isLoggedIn"  nz-button (click)="logout()">Se déconnecter</button>
...

1 Ответ

1 голос
/ 12 марта 2020

Я бы сказал, sessionStorage больше подходит для обработки пользовательских сессий. В случае проверки токенов, это также может помочь вам проверить его действительность. Попробуйте выполнить следующее:

login.service.ts

import { distinctUntilChanged } from 'rxjs/operators';

@Injectable({
  providedIn: 'root'
})
export class LoginService {
  private isLoggedInSource = new BehaviorSubject<boolean>(false);
  private isLoggedIn$ = this.isLoggedInSource.asObservable().distinctUntilChanged();

  public getIsLoggedIn(): Observable<boolean> {
    if (tokenValid()) {
      this.updateIsLoggedIn(true);
    }
    return this.isLoggedIn$;
  }

  public updateIsLoggedIn(state: boolean) {
   this.isLoggedInSource.next(state);
  }

  private tokenValid(): boolean {
    let result = false;
    const token = sessionStorage.getItem('token')
    if (token !== null) {
      const exp = (JSON.parse(atob(token.split('.')[1]))).exp;
      if ((Math.floor((new Date).getTime() / 1000)) < exp) {
        result = true;
      }
    }
    return result;
  }
}

Оператор distinctUntilChanged избегает нажатия избыточных значений.

login.component. ts

login(AuthenticationRequest) {
  this.loginService.login(AuthenticationRequest).subscribe(
    res => {
      sessionStorage.setItem('token', res.jwt);
      this.router.navigate(['patient/calendrier']);
      this.incorrect = false;
      this.loginService.updateIsLoggedIn(true);
    }, 
    error => {
      this.incorrect = true;
    }
  );
}

header.component.ts

export class HeaderComponent implements OnInit {
  private subscription;
  private isLoggedIn: boolean;

  constructor(private router: Router, private loginService: LoginService) { }

  ngOnInit() {
    this.today = new Date();
    this.subscription = this.loginService.getIsLoggedIn().subscribe(
      state => { this.isLoggedIn = state; }
    );
  }

  private logout() {
    sessionStorage.removeItem("token");
    this.loginService.updateIsLoggedIn(false);
    location.reload();
  }

  ngOnDestroy() {
    this.subscription.unsubscribe();
  }
}

header.component. html

<button *ngIf="isLoggedIn"  nz-button (click)="logout()">Se déconnecter</button>
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...