yaNastia
@yaNastia

Как сделать правильно toggle?

Когда юзер вошел, отображается: "Добро пожаловать + имя юзера", когда юpth выходит срабатывает гвард, и я присваиваю в "this.currentUser = null". При входе получаю ошибку Error: ExpressionChangedAfterItHasBeenCheckedError: Expression has changed after it was checked. Previous value: 'null: имя юзера'. Current value: 'null: '. Когда выхо;у, ловлю эту ошибку: TypeError: Cannot read property 'name' of null. Если убираю else, остается только ошибка с 'null'. Как пофиксить ?

export class AppComponent implements AfterViewChecked {
  toggle: boolean = false;
  user:string;

  constructor( private authService: AuthService, private cdRef : ChangeDetectorRef) {

  }

  ngAfterViewChecked() {
    let show = this.authService.isLoggedIn();
    if (show != this.toggle) { // check if it change, tell CD update view
      this.toggle = show;
      this.user = this.authService.currentUser.name;
      this.cdRef.detectChanges();
    }else {
      this.user = '';
    }
  }
}


<li>Welcome {{user}}</li>

logout(): void {
        this.currentUser = null;
        localStorage.removeItem('currentUser');
    }
  • Вопрос задан
  • 119 просмотров
Решения вопроса 1
if (show != this.toggle) { // check if it change, tell CD update view
      this.toggle = show;
      this.user = this.authService.currentUser.name;
    } else {
      this.user = '';
    }

    this.cdRef.detectChanges();


Нужно вызвать this.cdRef.detectChanges() после присвоения.
Ответ написан
Комментировать
Пригласить эксперта
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы