Issue
@Component({
selector: 'app-home2',
templateUrl: './home2.component.html',
styleUrls: ['./home2.component.scss']
})
export class Home2Component implements OnInit {
randNumberSub: BehaviorSubject<number> = new BehaviorSubject<number>(
Math.random()
);
ngOnInit() {
this.randNumberSub.subscribe((data) => {
console.log(`Sample1Component ==> RandomNumber: ${data}`);
});
}
onClick() {
this.randNumberSub.next(100);
}
}
I know that if I used a subject, for example, from a service that I injected, I would need to unsubscribe from it to avoid a memory leak, but if I use the subject only inside a component, will it unsubscribe when destroyed?
Solution
Every observable that doesn't complete needs to be explicitly unsubscribed.
In v16, Angular introduced the takeUntilDestroyed
operator that unsubscribes when the component is destroyed.
Answered By - Matthieu Riegler
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.