Reputation: 107
I have a component which has a method interval(), when a button is clicked.
interval() {
this.statusInterval = interval(2000).subscribe(x => {
this.interval2 = x;
console.log(this.interval2);
this.assetItemActionService.sendNumber(x);
})
}
In constructor I have this subscription which should update that value.
interval2 = 0;
percentSubscription= Subscription;
constructor(private service:Service) {
console.log('takeee');
this.percentSubscription = this.service.number$.subscribe(percent => {
console.log("set number");
this.interval2 = percent;
}, error => console.log(error))
}
The up 2 code fragments are in the same component.
In service I have this subject which is updated constantly.
private number: Subject<number> = new Subject();
number$ = this.number.asObservable();
sendNumber(number) {
console.log('received');
this.number.next(number);
}
The problem is when I route to another page, the UI is not updated, and the part from constructor is not working anymore, I can't subscribe, but in console the value is updated every time. So the UI is not rendered, and I can't subscribe anymore to that subject after I come back on component.
How I can solve this?
Upvotes: 0
Views: 438
Reputation: 39482
You should unsubscribe
the subscription
(s) that you have in the component.
The fact that you're still able to see logs on your console after leaving the component clearly indicate that you haven't unsubscribe
d from the subscriptions, which in turn is causing memory leaks.
Here, give this a try:
import { Component, OnInit } from "@angular/core";
import { Subscription, interval } from "rxjs";
import { NumberService } from "../number.service";
@Component({
selector: "app-some",
templateUrl: "./some.component.html",
styleUrls: ["./some.component.css"]
})
export class SomeComponent implements OnInit {
interval2 = 0;
percentSubscription = Subscription;
statusInterval;
constructor(private assetItemActionService: NumberService) {
console.log("takeee");
this.percentSubscription = this.assetItemActionService.number$.subscribe(
percent => {
console.log("set number");
this.interval2 = percent;
},
error => console.log(error)
);
}
ngOnInit() {
this.interval();
}
interval() {
this.statusInterval = interval(2000).subscribe(x => {
this.interval2 = x;
console.log(this.interval2);
this.assetItemActionService.sendNumber(x);
});
}
ngOnDestroy() {
this.percentSubscription.unsubscribe();
this.statusInterval.unsubscribe();
}
}
PS: You didn't specify what you're using in the template. So I've just added the routes to two components(some
, and hello
).
Here's a Working Demo for your ref.
Upvotes: 1