TheGreatZab
TheGreatZab

Reputation: 163

Subscription Code Firing off Incrementally Every Time Component Loads

In my component's ngOnInit I have the following:

public Subscription: Subscription;

ngOnInit() {
    this.subscription =  this.myService.currentData.subscribe( i => {
        this.currentData = i;
        this.function(this.currentData)
    });
}

When my component loads, I have it subscribe to some data in a service to later use in a function. Loading it the first time works great. However, when I load to another module then come back, the function will fire off two times. Every time I repeat this process the function will fire off and increment. Meaning if I switch in and out of the module say 5 times, the function will fire off 5 times.

My attempt at solving this was to add an unsubscribe to ngOnDestroy like so:

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

However this seems to do nothing as the issue still occurs.

Upvotes: 4

Views: 373

Answers (1)

TheGreatZab
TheGreatZab

Reputation: 163

Two issues were present. First off, I was declaring my Subscription incorrectly.

Instead of this:

public Subscription: Subscription;

This is what needs to be put:

public Subscription = new Subscription();

Also, instead of equating my Subscription to my subscribe statement, I switched to .add(). This allows me to have my subscription object be assigned to all subscribers and unsubscribe them in one go:

this.Subscription.add(this.myService.currentData.subscribe( i => {
    this.currentData = i;
    this.function(this.currentData)
}));

Upvotes: 2

Related Questions