After reloading the component, I encountered difficulties subscribing again to the BehaviorSubject for a second time

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.

Answer №1

If your child components are subscribing to the BehaviorSubject within the parent component, they will lose their subscription once you navigate away from the parent component - that is when it gets destroyed. The first child component may not be affected because it is likely on the same DOM as the parent, but the second child component is probably not, causing it to lose access to the Subject.

The best solution is to keep the BehaviorSubject in the service and have both the parent and children subscribe to it instead.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Leverage the compiler API to perform type inference

Exploring TypeScript's compiler API for basic type inference has proven to be a challenge with limited helpful information found in documentation or online searches. My goal is to create a function inferType that can determine and return the inferred ...

The TypeScript factory design pattern is throwing an error stating that the property does not

While working with TypeScript, I encountered an issue when trying to implement the factory pattern. Specifically, I am unable to access child functions that do not exist in the super class without encountering a compiler error. Here is the structure of my ...

Angular 2 - One-Stop Form Component for Creating and Modifying

Seeking advice on how to efficiently reuse my Form Component. Data Model: class Contact { id?: String; name: String; } When a new Contact is created, the id is optional in the model as it doesn't exist at that point. When editing a Contac ...

Encountering TypeScript errors while trying to implement Headless UI documentation

import { forwardRef } from 'react' import Link from 'next/link' import { Menu } from '@headlessui/react' const MyLink = forwardRef((props, ref) => { let { href, children, ...rest } = props return ( <Link href={href}&g ...

Provide a parameter for a function's callback

I am attempting to utilize lodash's debounce function to delay the onChange event. See the code snippet below. import React, { useState, useEffect, useCallback } from "react"; import { TopBar } from "@shopify/polaris"; import { debounce } from "lodas ...

What is the significance of requiring a specific string in a Typescript Record when it is combined with a primitive type in a union?

I am facing an issue with the following data type: type ErrorMessages = Record<number | 'default', string>; When I declare a variable like const text: ErrorMessages = {403: 'forbidden'}, Typescript points out that default is miss ...

What is the best way to determine if a user is currently in a voice channel using discord.js?

Is there a way for me to determine if a user is currently linked to a voice channel? I am trying to implement a command that allows me to remove a user from a voice channel, and here is how I am attempting to check: const user: any = interaction.options.ge ...

Is it possible to apply a formatting filter or pipe dynamically within an *ngFor loop in Angular (versions 2 and 4

Here is the data Object within my component sampleData=[ { "value": "sample value with no formatter", "formatter": null, }, { "value": "1234.5678", "formatter": "number:'3.5-5'", }, { "value": "1.3495", "formatt ...

Optimizing an ASP.NET web application for seamless integration with Angular 2 and TypeScript

For the past couple of days, I have been delving into angular2. I am curious to understand the process of configuring my project to effectively utilize angular2 and typescript. My development environment is Visual Studio 2015. Can you guide me on the nec ...

How can the `!` operator be utilized in MikroORM Typescript entities?

How can I declare a key in a JS object with an ! before the colon? MikroORM syntax for class @Entity() export class Post { // Using @PrimaryKey() decorator to designate primary key @PrimaryKey() id!: number; @Property({ type: "date", de ...

What could be the reason for the validation failure?

companyprofile.html <form #f="ngForm" name="companyProfileForm" ng-submit="companyFrmSave(objCS, objCSCurrency)" novalidate=""> <div class="row form-group"> <div class="col-md-12" > ...

Is it possible to use Angular *ngIf on a component while also binding ngStyle to a method

Currently, I am working with Angular 5 and grappling with an issue that may be related to either the Angular version or how I structured my components. The primary focus of my task involves creating a component resembling a table, comprising two key segme ...

Exploring methods to retrieve the status attribute of an Angular httpClient response

Here is the code snippet that I am working with: this.http.post(url, payload) .subscribe( (req:any)=>{ if(req.status != 200){ console.log('non 200 status'); The this.http in my code refers to a service tha ...

Having trouble resolving all parameters for 'Router' in Angular 2 testing with Router

Currently, I am in the process of testing a component that has Router injected in the constructor (TypeScript): constructor( private _router: Router, private dispatcher: Observer<Action>, fb: FormBuilder ) { ... } Here are the test cases ...

Learn how to trigger an HTTP exception after a failed command in a saga with NestJS CQRS

Currently utilizing the NestJS CQRS pattern to handle interactions between User and UserProfile entities within my system. The setup consists of an API Gateway NestJS server along with dedicated NestJS servers for each microservice (User, UserProfile, etc. ...

Tips for updating the color of checkboxes in an Angular application

I'm looking to update the appearance of a checkbox when it is disabled. app.component.html: <input type="checkbox" class="custom-control-input" [disabled]="item.disabled" [checked]="item.checked"> The cu ...

Angular subscription and observable continuously fetch information

I'm encountering an issue with utilizing subscriptions and observables Here is my code This is my inventory.service.ts getInventoryList = (page: string, pageSize,size) => { const userLocation = this.authService.getUserLocation(); let que ...

Tips for navigating back to the previous component in React:

Greetings! I'm currently working on a simple CRUD example using React.Js and TypeScript. In my project, I have set up the following component hierarchy: -FetchNaselje --Modal ---AddNaselje It's structured such that AddNaselje is a child of Moda ...

What is the best way to define a valid empty date in Moment js?

Currently, I am working with an Angular material datepicker that only allows the selection of a month and year. You can check out the functionality here: Angular Material Datepicker View Changes The issue I'm facing is that the datepicker doesn' ...

Angular shows nested values without considering dynamic keys

I need assistance with displaying user data retrieved from Firebase database. The JSON response I receive from Firebase starts with a dynamic value like "SivqCsErHQZNvGMe7p6r5nGknFy2". How can I skip this dynamic value and only show key/value pairs below? ...