What causes an ObjectUnsubscribedError to be triggered when removing and then re-adding a child component in Angular?

Within a parent component, there is a list:

items: SomeType;

The values of this list are obtained from a service:

this.someService.items$.subscribe(items => {
  this.items = items;
});

At some point, the list is updated with new criteria:

this.someService.getData(this.criteria);

This process functions correctly.


There is also a child component that is inserted for each element in the list:

<ul *ngFor="for let item of items">
  <app-list-item [item]="item"></app-list-item>
</ul>

This functionality works as expected, but only when the initial load of this.items in the parent component occurs.

The child component also retrieves data from a service:

ngOnInit() {
  this.someOtherService.mapping$.subscribe(mapping => {
    this.mapping = mapping;
  });
}

ngOnDestroy() {
  this.someOtherService.mapping$.unsubscribe();
}

However, when the criteria within the parent component change and the item list is reloaded, the child component encounters the following error message:

Error message: "object unsubscribed" name: "ObjectUnsubscribedError"

When I remove

this.someOtherService.mapping$.unsubscribe();
from the ngOnDestroy method of the child component, it functions properly again. But should I not unsubscribe when the component is destroyed?

Answer №1

Unsubscribing from a child in the correct manner is important. Remember, you should be unsubscribing from the observable, not the subscription itself. Here's how it should be done:

childSubscription: Subscription;

ngOnInit() {
  this.childSubscription = this.someOtherService.data$.subscribe(data => {
    this.data = data;
  });
}

ngOnDestroy() {
  this.childSubscription.unsubscribe();
}

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

Is there a method for PHP to detect changes in front-end routing (specifically with Angular)?

A scenario I am encountering involves having an angular form incorporated within a php page. The issue arises when the angular form is submitted and is supposed to navigate to a different page. In actuality, once the angular form is completed, it should u ...

The concept of Typescript involves taking a particular type and generating a union type within a generic interface

Picture a straightforward CollectionStore that contains methods for creating and updating a record. The create() method takes in a set of attributes and returns the same set with an added id property. On the other hand, the update method requires the set t ...

Utilizing MSAL to seamlessly retrieve tokens with the assistance of an HTTP interceptor

When encountering a 401 error in Angular, I am attempting to invoke the MSAL silentTokenrefresh method within the authInterceptor. The goal is to retrieve a new token and then retry the failed request seamlessly so that the service remains uninterrupted. F ...

Encountered an unexpected error while attempting to integrate my custom npm library "MyModule" into my Angular 2 project

I have created my own library which consists of one module and one component. After compiling my library, I add it to my main project using the following command: npm link ng-shared Next, when I attempt to import SharedModule in my module file as shown b ...

Modifying the values of various data types within a function

Is there a more refined approach to enhancing updateWidget() in order to address the warning in the else scenario? type Widget = { name: string; quantity: number; properties: Record<string,any> } const widget: Widget = { name: " ...

PrimeNG Component Containing a Dynamic Dialog Instance

I am experiencing an issue with handling dynamic dialogs in PrimeNG. Is there a solution for managing actions on a dialog other than just using the close option? For instance, in the context of the Kendo-UI dialog example, I can specify the content.insta ...

Encountered an error while loading resource: net::ERR_CONNECTION_REFUSED in Nodejs

I am currently working on a form in my angular 6 app with nodejs, utilizing nodemailer for sending emails. Unfortunately, I am encountering an error that reads: Failed to load resource: net::ERR_CONNECTION_REFUSED : :3000/contact/send:1 Below is the form ...

Is it possible for the link parameters array in Angular2 Routing to contain more than one element?

Currently delving into Angular2 on my own. According to the text I'm studying, when a user navigates to a feature linked to a route using the routerLink directive, the router employs both the link parameters array and the route configuration to constr ...

Encountering errors with ng build --prod in Angular 2, but no issues when running ng serve

After attempting to deploy my Angular 2 app to Heroku, I encountered a daunting list of errors when trying to build for production. Interestingly, the app runs smoothly without any issues or errors when using 'ng serve'. You can view the full li ...

Style the date using moment

All languages had a question like this except for JavaScript. I am trying to determine, based on the variable "day," whether it represents today, tomorrow, or any other day. ...

Typescript displays an error message when attempting to assign a list of string variants to a defined type

Encountering an interesting TS error in the code snippet below: interface Bar { pictureType: "X" | "Y" } interface RT { output: Bar[] } const func = (): RT => { const list = [{ pictureType: 'X', }] r ...

Protractor's compatibility with Headless Chrome is hindered on AWS CodeBuild, yet functions successfully when run locally

I am facing an issue with my webpage that requires Google Authentication before moving on to an angular web page. I have created some basic end-to-end tests which are working perfectly fine in Linux using Chrome Headless: The test finds the username fiel ...

Could we bypass the parent component somehow?

Just starting out with angular and decided to work on a small project. As I was setting up my routing, I encountered a problem. Here is the routing setup I have: const routes: Routes = [ {path: '', redirectTo: '/home', pathMatch: &a ...

IntelliJ is unable to locate the scss import when using the includePaths option in stylePreprocessorOptions

Having trouble with IntelliJ 2019.2.2 Ultimate not detecting scss imports from stylePreprocessorOptions - includePaths Here is the directory structure: https://i.stack.imgur.com/SQEDT.png In my angular.json file, I have specified: "stylePreprocessorOpt ...

Elements are receiving CSS properties from other elements within the same component

I'm encountering an issue with my components: 1. I cannot seem to style html and body in signin.component.css for some reason. The workaround I found was using: encapsulation: ViewEncapsulation.None ==> This works perfectly However, when I switch ...

Issue detected in React Rollup: the specific module 'name' is not being exported from the node_modules directory

Currently in the process of creating a library or package from my component. The tech stack includes React, Typescript, and various other dependencies. Encountering an error while using Rollup to build the package: [!] Error: 'DisplayHint' is ...

Using JSON objects as values in Angular2

When displaying a select option in my HTML, I am currently able to show a string as the value. However, I would like to have the entire JSON object as the value instead of just the string that is being displayed. Here is my code: <select *ngIf="car" c ...

In order to work with the optionSelectionChanges property of the MdSelect directive in Angular Material2, it

Within my application, there is a Material2 select dropdown widget containing several options. app.component.html <md-select placeholder="Choose an option" [(ngModel)]="myOption" (optionSelectionChanges)="setOptionValue(myOption)"> &l ...

Discovering the proper way to infer type for tss-react withParams and create

Greetings to everyone and a huge thank you in advance for your generous help. I have a desire to utilize the tss-react library for styling, particularly because I will be implementing Material UI components. As I delve into some documentation, the latest A ...

"Unlock the secret to effortlessly redirecting users to a designated page when they click the browser's back

So I'm facing the challenge of disabling the browser back button on multiple routes and sending requests to the backend is resulting in inconsistent behavior. I don't want to create a multitude of similar API requests each time. Currently, I have ...