Glen Elkins
Glen Elkins

Reputation: 917

Fire custom event from component without view

I am looking to be able to fire a custom event that other components can subscribe to, what i've read isn't really what i want, i don't want any view or user interaction on a html element to fire my event.

If i have a component with a logout method:

logout() : void {
    // change local storage state

    // fire event so other components can update
}

I want this method to fire a custom event that other components can subscribe to so they know to react to the logout.

So another component might have a method:

something() : void{

    // subscribe the event here and perform some local action, like changing a login state variable
}

I'm sure i have done this before when i was using Ionic instead of pure angular...

Upvotes: 0

Views: 81

Answers (1)

Henrique Erzinger
Henrique Erzinger

Reputation: 1147

I believe the best approach for this pattern in Angular would be to expose an Observable with a service. Something like (say, in AuthenticationService):

private loginStatusSource$ = new BehaviorSubject();

public loginStatus$ = this.loginStatusSource$.asObservable();

...

logout() : void {
    // change local storage state

   this.loginStatusSource$.next(false);
}

getLoginStatus(): Observable<boolean> {
  return this.loginStatus$;
}

then in your component:

public loginStatus$: Observable<boolean>;

constructor(private authService: AuthenticationService) {
  this.loginStatus$ = this.authService.getLoginStatus();
}

something() : void{
  this.loginStatus$.subscribe(status => {
    // perform some local action...
  });
}

Note that this is a simplified exemple, you might want to store more than just a boolean, like your user data and stuff like that. State management tools like NGRX or Akita could be used, but this is the simpler, no additional dependencies required, approach I use.

Upvotes: 1

Related Questions