Subscription Code Firing off Incrementally Every Time Component Loads

喜夏-厌秋 提交于 2019-12-10 21:28:46

问题


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.


回答1:


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)
}));


来源:https://stackoverflow.com/questions/57715390/subscription-code-firing-off-incrementally-every-time-component-loads

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!