After reading recommendations to always unsubscribe when removing a component, I encountered an issue in my code. The error object unsubscribed
occurs when navigating between child components and trying to resubscribe to a BehaviorSubject. Even though I am subscribing again in the component's constructor, the error persists when moving back and forth between components. Removing the unsubscribe code from ngOnDestroy prevents the error but leaves the BehaviorSubject unsubscribed. This confusion prompts me to question when exactly should I unsubscribe? If not when removing a child component, then when? Below is the relevant part of my code:
export class TemperatureSettingsComponent implements OnInit, OnDestroy {
data: any;
temperatureForm: FormGroup;
monthlyTemperatureCurve: number[];
saveToLocalStorage: BehaviorSubject<any[]> = this.seedCalendarService.getSaveBehaviorSubject();
useImperialMeasureSystem: boolean = true;
options = {
responsive: false,
maintainAspectRatio: false
};
constructor(private fb: FormBuilder,
private seedCalendarService: SeedCalendarService,
private notificationService: NotificationService,
private dataStoreService: DataStoreService) {
this.saveToLocalStorage.subscribe(pair => {
if(pair[0] === DataType.MEASURE_SYSTEM_PREFERENCE){
this.useImperialMeasureSystem = pair[1];
}
});
this.temperatureForm = fb.group({
'january' : [''],
'february' : [''],
'march' : [''],
'april' : [''],
'may' : [''],
'june' : [''],
'july' : [''],
'august' : [''],
'september' : [''],
'october' : [''],
'november' : [''],
'december' : ['']
});
}
ngOnDestroy(){
this.saveToLocalStorage.unsubscribe();
}
Despite attempting to resubscribe to the BehaviorSubject in the constructor, it seems that only the initial instance of a child component can successfully subscribe and unsubscribe. Subsequent instances are unable to resubscribe, even though they represent new instances of the component. Can anyone provide clarification on this behavior? Thank you.