Search code examples
angulareventemitter

Clear MessageService ClickEventEmitter message history


I have a component in a shared header that emits a click event with a message whenever it's clicked. I have multiple pages with components that each subscribe to this MessageService and act on click events.

The problem is that when I switch to a new page, all previous messages are broadcast as well as the new one.

Is there a way to clear the old messages before sending one?

Header Button Code:

<div id="applyDate">
    <button (click)="applyClick()" id="applyBtn" class="btn btn-success btn-sm">Apply</button>
</div>

applyClick(){
    this.messageService.clickEventEmitter.emit("Start^"+this.start+"|End^"+this.end);
}

Component Subscription:

this.subscription = this.messageService.clickEventEmitter.subscribe(message => {
    let segs = message.split("|");
    this.start = segs[0].split("^")[1];
    this.end = segs[1].split("^")[1];

    console.log(this.start);
    console.log(this.end);
});   

When I jump to a "new page" (single page app). All of the messages sent on the previous page are sent and logged.

Example:

  1. Click Header
  2. Logs start and end (2 logs - expected)
  3. Click to new tab
  4. Click Header
  5. Logs start, end, start, end (4 logs - not expected)

Solution

  • The first issues is that I was not destroying the subscription when the component was destroyed:

    ngOnDestroy(){
        this.subscription.unsubscribe();
    }
    

    The bigger issue is that since I'm broadcasting similar messages to all components subscribed, they were all picking the message up and acting on it. I decided to reset each subscription after I received a message and this solved the problem.

    subscribe = () => {
        this.subscription = this.messageService.clickEventEmitter.subscribe(message => {
            let segs = message.split("|");
            this.start = segs[0].split("^")[1];
            this.end = segs[1].split("^")[1];
    
            console.log(this.start);
            console.log(this.end);
            this.resetSubscription();
        });  
    }
    
    resetSubscription = () => {        
        this.subscription.unsubscribe();
        this.subscribe();
    }