0
votes

I have created a service and did subscribe from my component

deleteSelected(action) {
    let data = {
      action: action,
      filterMessages: []
    }
    data.filterMessages = this.state.messages.filter((it) => it.selected);
    if (data.filterMessages.length > 0) {
      **this.messages.next(data);**
    } else {
      this.messageDetail.next(data);
    }
  } 

My component have the subscribed function

this.activeFolderSub = this.route.params.subscribe(params => {
this.folderName = params['folder'];

 this.messageSub = this.googleService.messages.subscribe(message => {
  this.messageIndex = 0;
    const moveToTrashMessage = message.filterMessages;
    const messageIds = [];
    const labelsToAdd = [];
    const labelsToRemove = [];
    labelsToAdd.push(message.action);
    labelsToRemove.push(this.folderName);
    moveToTrashMessage.forEach((it) => { messageIds.push(it.id) });      
    if (messageIds && messageIds.length > 0) {
      this.googleService.modifyMessages(messageIds, labelsToAdd, labelsToRemove).subscribe(messages => {
        if (messages.result && this.messageIndex == 0) {              
          this.toastr.success('Conversations have been moved! ', 'Success!');
          this.getAllMessageList(this.folderName, null);
           this.messageIndex++;
        }
      });
    }
  }
  );
});

And i also unsubscribe this function on ngOnDestroy But the problem in the function calling itself multiple times, i think it is because of duplicate subscribes.

When the first time component load itself its working fine but when i change the params value and its open that component again with different param value than the problem occurs. i think i have subscribed the service subject it subscribes again with duplicate subscribers. this is the screenshoot

2
Are you using an ngFor loop in your component markup? If so, there's a method that may help prevent the extra calls. Can you post a snippet. - ShellNinja
As a side note, I see two levels of nested subscriptions. Nested subscriptions are usually good candidates for flatMap/mergeMap - Sam Herrmann
Exactly, I was expecting to see it in the markup - but @SamHerrmann is correct good catch - ShellNinja

2 Answers

3
votes

I think you're just losing your reference to that subscription without cleaning it up. Just check if it's set and clear it before moving onward.

if (this.messageSub) {
    this.messageSub.unsubscribe();
}

this.messageSub = this.googleService.messages.subscribe(message =>
1
votes

You could make a array of subscriptions and on ngOnDestroy unsubscribe of them all:

private subs: Subscription[] = [];

this.subs.push(
    this.messageSub = this.googleService.messages.subscribe(n => {
        //your code here
    });
}

ngOnDestroy() {
    this.subs.forEach(n => {
        n.unsubscribe();
    });
}