Michael Irwin
Michael Irwin

Reputation: 3149

Notify Angular 2 component of change from a service

Using Angular 2, I have an AuthService that handles authentication. I'm trying to figure out the best way to notify other components when a user has logged in/out, but am unsure of the right way to handle this scenario. Any suggestions? Thanks!

Upvotes: 3

Views: 1372

Answers (1)

Bazinga
Bazinga

Reputation: 11234

The best way is to use BehaviorSubject.

class AuthService {

private _isLoggedIn:Subject<boolean> = new BehaviorSubject<boolean>(false);

  getUser() {
      return !!localStorage.getItem('user');     
  };

  isLoggedIn() {
    this.getUser() && this._isLoggedIn.next(true);
    !this.getUser() && this._isLoggedIn.next(false);
    return this._isLoggedIn.asObservable();
  }
}

// In your component

class NavComponent {
    constructor(private AuthService: AuthService) {
        this.AuthService.isLoggedIn().subscribe(status => this.isLoggedIn = status);
    }
}

Upvotes: 5

Related Questions