Reputation: 61
I have actually this code:
ComputerValue: number;
private subscription: ISubscription;
ngOnInit() {
this.getMyValue();
setInterval(() => {
this.getMyValue();
}, 30000);
}
getMyValue(): void {
this.subscription = this.dataService.getValueOfComputer().subscribe(data => {
console.log(data);
this.ComputerValue = data;
});
}
When i check my console, i have my result two time because i don't know why my subscribe execute my HTTP query twice.
Someone have an idea ?
Thanks !
Upvotes: 1
Views: 134
Reputation: 61
FIXED
I was using 2 component (AppComponent, ExampleComponent) where ExampleComponent was the code above.
I added ExampleComponent in my NgModule (declarations and Bootstrap array).
@NgModule({
imports: [BrowserModule, HttpClientModule, BrowserAnimationsModule, FormsModule, ChartsModule],
declarations: [AppComponent, ExampleComponent],
bootstrap: [AppComponent, ExampleComponent],
providers:[DataService]
})
When I removed ExampleComponent from Bootstrap Array, my HTTP requests stopped to be duplicated.
If someone have an answer for that do not hesitate
Upvotes: 0
Reputation: 39432
You're using setInterval
instead of setTimeout
. Your getMyValue
method will get called every 30 secs.
You're also calling getMyValue
two times. Once inside the ngOnInit
and once inside ngOnInit
's setInterval
Your getMyValue
gets called once for the first time it is called inside ngOnInit
and then it will get called after every 30 secs. Change your implementation like this:
ComputerValue: number;
private subscription: ISubscription;
ngOnInit() {
setInterval(() => {
this.getMyValue();
}, 30000);
}
getMyValue(): void {
this.subscription = this.dataService.getValueOfComputer().subscribe(data => {
console.log(data);
this.ComputerValue = data;
});
}
Not sure why you're doing that though.
Your scenario looks like a perfect example of Memory Leaks. And this happened to me while I was creating this Stackblitz for your reference.
Apparently, why you're getting two(or in my case, MANY) console logs is because you might have not unsubscribed from the subscription.
I thought of doing that later when I was compiling that StackBlitz. But then I noticed getting multiple logs to the console with different texts as I was still writing the code to be shown on the console.
unsubscribe
from the subscription first. Then reload the page and check if it's working as expected. I did it myself and it started working for me.
ngOnDestroy() {
this.subscription && this.subscription.unsubscribe();
}
PS: To replicate your scenario, comment out the ngOnDestroy
method and then change the contents of the log one by one while saving each change. You'll see multiple logs to the console and this time, NOT EVERY 30 secs.
Upvotes: 6