Я пытаюсь разделить переменную между двумя независимыми компонентами.
Работает нормально, пока я не обновлю 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>
...