简体   繁体   English

从没有视图的组件中触发自定义事件

[英]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.我希望能够触发其他组件可以订阅的自定义事件,我读到的并不是我真正想要的,我不希望 html 元素上的任何视图或用户交互来触发我的事件。

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...我确定我之前使用 Ionic 而不是纯 angular 时已经这样做了...

I believe the best approach for this pattern in Angular would be to expose an Observable with a service.我相信 Angular 中这种模式的最佳方法是使用服务公开 Observable。 Something like (say, in AuthenticationService):类似于(例如,在 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.请注意,这是一个简化的示例,您可能想要存储的不仅仅是 boolean,比如您的用户数据等。 State management tools like NGRX or Akita could be used, but this is the simpler, no additional dependencies required, approach I use.可以使用像NGRXAkita之类的 State 管理工具,但这是我使用的更简单的方法,不需要额外的依赖项。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM