Base solution for your next web application
Open Closed

Angular: unsubscribe from abp.event - how? #4697


User avatar
0
alexanderpilhar created

I'm having troubles trying to unsubscribe from some custom event. I use SignalR to trigger an event once an entity gets updated and everything is working fine so far. But when I leave the component and come back to it later, the event will be received for another (although it only gets triggered once, both on erver side as well as on client side - I already checked on that). The more times I leave and come back to the component, the more times the event will be received.

I read the documentation about subscribing and unsubscribing on [https://aspnetboilerplate.com/Pages/Documents/Javascript-API/Event-Bus]) and since unsubscribing isn't demonstrated by example, I came up with this:

private subscribe(): void {
   abp.event.on(this.evGetUpdate, (data) => this.onGetUpdate(data));
}

private unsubscribe(): void {
   abp.event.off(this.evGetUpdate, (data) => this.onGetUpdate(data));
}

onGetUpdate(data: any): void {
   console.log("event received:");
   console.log(data);
}

I think this is how it should work, but no luck. Btw: I'm calling subscribe() in ngOnInit() and unsubscribe() in ngOnDestroy() which are also executed as expected.

Please, give me some advice on how to unsubscribe from abp.event correctly!


3 Answer(s)
  • User Avatar
    0
    aaron created
    Support Team

    Those 2 arrow functions are different instances.

    abp.event.on(this.evGetUpdate, this.onGetUpdate);
    
    abp.event.off(this.evGetUpdate, this.onGetUpdate);
    
  • User Avatar
    0
    alexanderpilhar created

    Oh, how could I just do it wrong :roll: :lol: Thanks a lot, @aaron !

  • User Avatar
    0
    alexanderpilhar created

    I encountered some other problems with my original example: the way I declared the callback function that is used for subscribing and unsubscribing just wouldn't let me access any properties of my class. The declaration that now does work looks like this:

    onGetUpdate = (data: MyClass) => {
       this.item = data;
    }
    

    Just to let you know ;)