0

I have a navbar component, inside its ngOnInit function I have checked if user is logged in or not, if the user is logged in then I change isAuthorized to true, and its default is false, then I check with *ngIf="isAuthorized", in my menu lis. Now when the user is not logged in some of my menu items are not created, and when the user clicked on the post like button, I have checked to show login modal if the user is not logged in. After user logged in, I can change isAuthorized of navbarComponent from false to true, but my navbar component can't detect the changes and create other menus. Inside login function I have: this.navbar.refresh(); after I have set token, and inside navbar component, I have a refresh function:

refresh() {
    this.isAuthorized = true;
    this.changeDetector.detach();
    setInterval(() => {
      this.changeDetector.reattach();
      // if (!this.changeDetector['destroyed']) {
        this.changeDetector.detectChanges();
      // }
      this.changeDetector.detach();

    }, 10000);
  }

The main thing I want is to prevent from reloading when a user logged in with modal, and show other menu items.

jones
  • 1,423
  • 3
  • 35
  • 76

2 Answers2

0

change detection isn't your problem since ngOnInit gets called only once initiating the navbarComponent ..

a highly candidate solution i use, is to define a Subject<boolean> isLoggedIn and in the navbarComponent you subscribe to it at ngOnInit

 isLoggedIn.asObservable().subscribe(newVal => isAuthorized = newVal);

when the user logs in you push the value true like

 this.isLoggedIn.next(true);

the subscribtion will automatically fire each time isLoggedIn changes then isAuthorized change also

here is a good example of encapsulating this in a service

Additional Advice

use localStorage to store the token so a user won't need to enter his credintials each time he refreshes ..

Modar Na
  • 873
  • 7
  • 18
0

Your problem relate to maintain the state of the application. We can use rjxs/BehaviorSubject to keep the state and we can get rid of ChangeDetectorRef

// auth.service.ts

import { Injectable } from '@angular/core';
import { BehaviorSubject } from 'rxjs/BehaviorSubject';

@Injectable()
export class AuthState  {
  private auth$ = new BehaviorSubject<boolean>(false);

  public login() {
    return this.auth$.next(true);
  }

  public logout() {
    this.auth$.next(false);
  }

  public isLoggedIn() {
    return this.auth$.asObservable();
  }
}

In navbar component and template

constructor(public authState: AuthState) {
  this.authState.isLoggedIn().subscribe((isAuth) => {
    // do something
  }
}

In login component (somewhere)

this.authState.login()

Hope this help.

For complex state - management, checkout @ngrx/platform

hienduyph
  • 94
  • 1
  • 4