Andayz
Andayz

Reputation: 155

Angular 2 - conditional header

I have a header with a few buttons such as Home, About us, Register, Log in, Log out, Register and I want to show all except Log in and Register when user is logged in and only those two if user isn't logged.

I know that I can use something like this:

<li *ngIf="!isUserLoggedIn"><a href="#">Log in</a></li>
<li *ngIf="isUserLoggedIn"><a href="#">Log out</a></li>
<li *ngIf="!isUserLoggedIn"><a href="#">Register</a></li>

but it's probably a bad idea to call a service from a header to check whether user is logged and initialize this variable. Am I right ?

Upvotes: 1

Views: 2299

Answers (1)

Bruno Jo&#227;o
Bruno Jo&#227;o

Reputation: 5545

What I did was:

1 - Create an Auth Service that is responsable for set a variable that represents the auth status.

2 - Set the auth status variable to an Observation one;

3 - On the header component you can subscribe to this auth service variable observer and then change the header mode based on the auth variable status.

For example:

auth.service.ts

Ps. Notice the localStorage.getItem('authState') when declaring the authStateSubject. This way you can get the current state of the user.

...
@Injectable()
export class AuthService {

  // you can get the actual state from memory here
  private authStateSubject: BehaviorSubject<Boolean> = new BehaviorSubject<Boolean>(localStorage.getItem('authState'));

  state: Observable<Boolean> = this.authStateSubject.asObservable();
...

header.component.ts

...
@Component({
  ...
})

export class SidenavLeftComponent {

  isUserLoggedIn: boolean;

  constructor(private authService: AuthService) {
    ...
  }

  ngOnInit(){
    // update auth status when it changes
    this.authService.state.subscribe(state => this.isUserLoggedIn = state);
  }

}
...

header.component.html

...
<li *ngIf="!isUserLoggedIn"><a href="#">Log in</a></li>
<li *ngIf="isUserLoggedIn"><a href="#">Log out</a></li>
<li *ngIf="!isUserLoggedIn"><a href="#">Register</a></li>
...

When the user logs in, you call this method in the auth.service.ts this.authStateSubject.next(true);

When the user logs out, you call this method in the auth.service.ts this.authStateSubject.next(false);

That way, all subscribers will notice the new value and act over it.

Upvotes: 1

Related Questions