A
A
asd dsa2018-11-23 23:45:06
JavaScript
asd dsa, 2018-11-23 23:45:06

How to do the right toggle?

When the user is logged in, it displays: "Welcome + username", when yupth logs out, the guard is triggered, and I assign "this.currentUser = null" to "this.currentUser = null". When I log in I get an error Error: ExpressionChangedAfterItHasBeenCheckedError: Expression has changed after it was checked. Previous value: 'null: username'. Current value: 'null: ' . When I exit, I catch this error: TypeError: Cannot read property 'name' of null . If I remove the else, only the 'null' error remains. How to fix?

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');
    }

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Dmitry Luzanov, 2018-11-24
@yaNastia

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();

Must be called this.cdRef.detectChanges()after assignment.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question