Experiencing issues with unsubscribing in an Angular application?

Attempting to subscribe for a REST call

this.empObs0 = this.fetchData.getEmployeeInfoToUpdate(JSON.parse(this.empName0)).subscribe(
  data0 => {
    this.emp_DBRows0 = <EmpUpdateModel[]> data0;
  },
  error => {
    console.log(error);
  }
);

FetchDataService.ts

// Fetches employee information for updating
getEmployeeInfoToUpdate(jsonArray: JSON): Observable<EmpUpdateModel[]> {
  console.log('GET getEmployeeInfoToUpdate');
  this.dataGS =  this.http.post<Observable<EmpUpdateModel[]>>('/api/getEmployeeInfoToUpdate', jsonArray);
  return this.dataGS;
}

I need to unsubscribe in the ngOnDestroy() method

// Destroying the component.
ngOnDestroy() {
  console.log('Destroy called');
  this.empObs0.unsubscribe();
}

However, encountering an error while trying to destroy it.

ERROR Error: Uncaught (in promise): TypeError: Cannot read property 'unsuscribe' of undefined
TypeError: Cannot read property 'unsuscribe' of undefined
    at UpdateTeamRosterComponent.push../src/app/components/update-team-roster/update-team-roster.component.ts.UpdateTeamRosterComponent.ngOnDestroy (update-team-roster.component.ts:176)
    at callProviderLifecycles (core.js:18943)
    at callElementProvidersLifecycles (core.js:18911)
    at callLifecycleHooksChildrenFirst (core.js:18901)
    at destroyView (core.js:19963)
    at callWithDebugContext (core.js:20722)
    at Object.debugDestroyView [as destroyView] (core.js:20406)
    at ViewRef_.push../node_modules/@angular/core/fesm5/core.js.ViewRef_.destroy (core.js:18232)
    at ComponentRef_.push../node_modules/@angular/core/fesm5/core.js.ComponentRef_.destroy (core.js:18068)
    at RouterOutlet.push../node_modules/@angular/router/fesm5/router.js.RouterOutlet.deactivate (router.js:4858)
    at resolvePromise (zone.js:814)
    at resolvePromise (zone.js:771)
    at zone.js:873
    at ZoneDelegate.push../node_modules/zone.js/dist/zone.js.ZoneDelegate.invokeTask (zone.js:421)
    at Object.onInvokeTask (core.js:14134)
    at ZoneDelegate.push../node_modules/zone.js/dist/zone.js.ZoneDelegate.invokeTask (zone.js:420)
    at Zone.push../node_modules/zone.js/dist/zone.js.Zone.runTask (zone.js:188)
    at drainMicroTaskQueue (zone.js:595)
    at ZoneTask.push../node_modules/zone.js/dist/zone.js.ZoneTask.invokeTask [as invoke] (zone.js:500)
    at invokeTask (zone.js:1540)

Seeking assistance with resolving this issue.

Answer №1

Make sure to check if the Observable is stored in a variable before attempting to unsubscribe. If there was an error while storing the observable, the variable value could be undefined. Always verify if it is defined before unsubscribing.

// Clean up the component.

ngOnDestroy() {
  if(this.empObs0) 
    this.empObs0.unsuscribe();
}

If you have multiple observables, it's advisable to follow @sachila's advice for handling them properly.

Answer №2

To follow a recommended approach, consider creating a subscription array and adding subscriptions to it. Then, during the destroy cycle, unsubscribe from them by iterating through the array.

subscriptions: Subscription[] = [];


this.subscriptions.push(this.getData.fetchInfo(JSON.parse(this.itemName)).subscribe(
  response => {
    this.dataArray = <DataModel[]> response;
  },
  error => {
    console.log(error);
  }
));

 ngOnDestroy() {
        this.subscriptions.forEach(subscription => {
            subscription.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

I'm having trouble locating Deploy in Ionic 2

Recently, I followed the Ionic documentation to set up Ionic Deploy on an application. However, upon implementation, I encountered this error: 'Cannot find name 'Deploy'. I diligently followed the instructions provided at: . Below is a snip ...

Angular2 - The Iterable Differ fails to detect changes

I am currently utilizing the Iterable Differs feature in Angular2 to monitor changes in my data. However, I am facing an issue where the differ.diff method always returns "null" and I am unsure of the reason behind this. constructor(differs: IterableDiffe ...

best practices for choosing items from a dropdown menu using Angular

I have a dropdown list displaying existing tags/chips created by users in the past. However, I'm having an issue where when I select a tag from the dropdown list, it doesn't show up in my input field (similar to the Chart tag currently). I am abl ...

ngx-translate is failing to display any text within a lazily-loaded module

We are currently utilizing Angular 6 within our application and have recently initiated the process of preparing our app for lazy-loading. Our application consists of multiple lazy-loaded routes, and our goal is to utilize a single language file for all ro ...

"Learn how to automatically limit date selection to a maximum of 3 days after choosing a date with the nb-rangepicker rangep

I have successfully implemented the nebular date range picker to filter data. However, I am facing an issue with setting the default maxDate 3 days after selecting the input. I have tried multiple methods but none have worked for me. Below is my TypeScript ...

"Proper Installation of Angular Project Dependencies: A Step-by-Step

Whenever I clone an Angular project with older versions that are missing the node_modules folder, and then run npm install to install all necessary dependencies, I end up receiving numerous warnings and errors related to version mismatches. Here are some ...

The file that is currently being downloaded has the .pptx extension, but it is being

Take a look at this code snippet: const generateDownload = ({ link, data, title, settings })=> { const newLink = document.createElement('a'); const blobUrl = link || URL.createObjectURL(new Blob([data], settings)); newLink.setAt ...

Validation of email forms in Angular 5

I have encountered a challenge that I need help with: Using Angular 5 - template driven form In my template, there is an input field with the type email. Here's an example: <input type="email" [(ngModel)]="model.email" #email="ngModel" email /> ...

cdkDropList does not function properly when used with ng-template in a dynamic component list

Exploring the new Drag&Drop features introduced in Angular Material 7, I am dynamically generating components using ng-template. <div cdkDropList (cdkDropListDropped)="dropLocal($event)"> <ng-template #components></ng-templat ...

The Relationship Between Typing Variables and Generic Types in Functions

I need help implementing a specific function type: type TestType<T extends HTMLElement> = (input: T) => React.Ref<T>; I have a variable that I want to be typed with the above type for strict type guarantees on the return type: const Test ...

Error: NullInjectorError for AviorBackendService as there is no provider even though it has been provided

Here is the test code I have: import { TestBed, inject } from '@angular/core/testing'; import { AviorBackendService } from './avior-backend.service'; import { HttpClientTestingModule, HttpTestingController } from '@angular/common ...

Tips for showing a Dialog box in reference to multiple rows in a table

Objective: Retrieve data and showcase it in a dialog box using the button located in the Button column. Essentially, clicking on one of the buttons will display the corresponding data in the dialog. Challenge: Currently, I can only extract hardcoded s ...

Include quotation marks around a string in C# to convert it into JSON format

I am utilizing a service that operates with JSON format. However, the JSON data I am receiving does not include double quotes around keys and values. Here is an example of the data I have: [{name:{buyerfirstname:Randy, buyermiddlename:null, buyerlastnam ...

Display data in a template upon receiving a response from the server

Hello, I am currently in the process of developing my very first Angular application and could use some assistance. Specifically, I am working on a component that serves as an image search box. When a user inputs a search query, a request is sent to an API ...

Dealing with the "this" problem in TypeScript and its impact on scope

Here is my code snippet: class MyClass { name = "MyClass"; // traditional method definition getName1(){ return this.name; } // method defined as an arrow function getName2 = () => { return this.name; ...

Error TS2339: The property 'SOLDE' is not found in the 'AdvTitres' type

I am working with an array and need to retrieve the value of the SOLDE variable. You can find the JSON file here. When I try to access the SOLDE property, I get the following error message: error TS2339: Property 'SOLDE' does not exist on type ...

Angular along with HTTP struggles to interpret JSON data - The property 'json' is not recognized on the type 'Object'

Recently, I made the upgrade to Angular version 7. Here's how it happened: const httpOptions = { headers: new HttpHeaders({ 'Content-Type': 'application/json', 'Authorization': 'Bearer ' ...

My browser is able to display the JSON response from an HTTP request, as well as the REST client, but

I am attempting to access my own endpoint on a subdomain managed by Nginx. I anticipate the request to fail and return a JSON payload structured like this: { "hasError": true, "data": null, "error": { " ...

Is it possible to utilize MongooseArray.prototype.pull() in typescript?

A problem has arisen in Typescript at this specific line of code: user.posts.pull(postId); An error message I'm encountering states: Property 'pull' does not exist on type 'PostDoc[]' The issue seems to be related to the fac ...

Exploring ways to simulate an event object in React/Typescript testing using Jest

I need to verify that the console.log function is triggered when the user hits the Enter key on an interactive HTMLElement. I've attempted to simulate an event object for the function below in Jest with Typescript, but it's not working as expecte ...