Encountering an issue with Angular 12: The error message "TypeError: teardown.unsubscribe is

Since updating my app to Angular 12, I've been encountering an unusual error message every time I move away from a component that has ngOnDestroy function with .unsubscribe() calls. What's even more peculiar is that the teardown.unsubscribe mentioned in the error isn't present anywhere in my project, which is making it quite challenging to troubleshoot.

ERROR Error: Uncaught (in promise): UnsubscriptionError: 1 errors occurred during unsubscription:
    1) TypeError: teardown.unsubscribe is not a function
Error
    at _super (createErrorClass.js:4)
    at new UnsubscriptionErrorImpl (UnsubscriptionError.js:3)
    at SafeSubscriber.unsubscribe (Subscription.js:55)
    at SafeSubscriber.unsubscribe (Subscriber.js:55)
    at FooComponent.ngOnDestroy (my-foo.component.ts:58)
    at executeOnDestroys (core.js:7406)
    at cleanUpView (core.js:7309)
    at destroyViewTree (core.js:7142)
    at destroyLView (core.js:7287)
    at RootViewRef.destroy (core.js:22651)
    at resolvePromise (zone.js:1213)
    at resolvePromise (zone.js:1167)
    at zone.js:1279
    at ZoneDelegate.invokeTask (zone.js:406)
    at Object.onInvokeTask (core.js:28667)
    at ZoneDelegate.invokeTask (zone.js:405)
    at Zone.runTask (zone.js:178)
    at drainMicroTaskQueue (zone.js:582)
    at ZoneTask.invokeTask [as invoke] (zone.js:491)
    at invokeTask (zone.js:1600)

my-foo.component.ts

57: ngOnDestroy(): void {
58:     this.aSubscription$?.unsubscribe();
59:     this.bSubscription$?.unsubscribe();
60:     this.cSubscription$?.unsubscribe();
61:     this.dSubscription$?.unsubscribe();
62: }

Answer №1

When subscribing to something, do it like this:

 let subscription = this.someSubscription$.subscribe(() => {
      /// Your code goes here
    });

To clean up in the ngOnDestroy() method, add:

subscription && subscription.unsubscribe()

Answer №2

In all honesty, none of the existing patterns seem ideal. Here's a more efficient approach:

private unsubscribeHandler$: Subject<any> = new Subject()

ngOnInit() {
  this.myService.pipe(takeUntil(this.unsubscribeHandler$)).subscribe()
}

ngOnDestroy() {
  this.unsubscribeHandler$.next()
  this.unsubscribeHandler$.complete()
}

NOTE:

.pipe(takeUntil(this.unsubscribeHandler$))
handles the unsubscribe process - just include this for each subscription to reduce code repetition. By adopting this method, your issues will be resolved swiftly...

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

Apply a class using [ngClass] based on an HTML condition within the local scope

In the past, I have utilized [ngClass] to assign classes based on the Boolean value of a variable in the JavaScript/TypeScript. However, I am now curious if it is achievable to apply [ngClass] based on a local HTML boolean value instead? For example: < ...

Do you have an index.d.ts file available for canonical-json?

I am currently working on creating an index.d.ts file specifically for canonical-json. Below is my attempted code: declare module 'canonical-json' { export function stringify(s: any): string; } I have also experimented with the following sn ...

Update the header background color of an AG-Grid when the grid is ready using TypeScript

Currently working with Angular 6. I have integrated ag-grid into a component and I am looking to modify the background color of the grid header using component CSS or through gridready columnapi/rowapi. I want to avoid inheriting and creating a custom He ...

Ways of invoking a component method from a service in Angular 2

I have a concept for creating a unique service that is capable of interacting with one specific component. In my application, all other components should have the ability to call upon this service and then have it interact with the designated component in ...

Having trouble with CORS configuration - one API method is accessible while another is not?

Whenever I try to access method A, it works fine, but method B gives me a CORS error: The preflight request response does not pass the access control check: There is no 'Access-Control-Allow-Origin' header present on the requested resource. He ...

Remap Objects Function with Correct Return Data Type

After receiving data from another source via a post request in a large object, I need to extract specific fields and organize them into more precise objects with some fields remapped before inserting them into a database. Currently, I have a working solut ...

A collection of objects in TypeScript with a reference and the ability to add new objects using the

Recently, I've come across an issue in my code while working with custom objects and arrays of them. I have identified a scenario where the push() method works fine and another where it doesn't. Scenario 1 (working as expected): class MyObject{ ...

Reusing Ionic headers across multiple pages

I'm looking to reuse my HTML header across different pages within an Ionic 4 app. Here is a snippet of my code: header.html <ion-view> <ion-grid> <ion-row> <ion-col col-6 class="font"> < ...

SolidJS does not support reactivity for arrays of objects

I've been scratching my head trying to figure out why this code isn't working as expected. I'm simply updating an object and expecting it to be refreshed in the DOM, but for some reason, that's not happening. The console log confirms th ...

Executing Typescript build process in VSCode on Windows 10 using Windows Subsystem for Linux

My configuration for VSCode (workspace settings in my case) is set up to utilize bash as the primary terminal: { "terminal.integrated.shell.windows": "C:\\WINDOWS\\Sysnative\\bash.exe" } This setup allo ...

Using TypeScript for Type Inference in Fetch Operations

I created a custom Fetch wrapper in Typescript to fetch data from my API. I am facing an issue where the retrieved data is of type "any" and I want to convert it to a specific type, like "user". Here is the link to my codesandbox for reference: https://co ...

It is not possible to repeatedly hear the same event on a single element

It seems that I am unable to listen to an event multiple times on a single element. Upon investigation, I have found the following observations: This issue arises when triggering an RxJS observable from lifecycle methods such as ngAfterViewChecked, ngDoC ...

Emulate an HTTP Observable response using a subject

In the realm of Angular 4, I have crafted a service that currently relies on an HTTP request to produce an Observable of type Comment. return this.http.post(targetUrl, JSON.stringify({ 'Text': comment.Text, 'ThreadId': threadId }), op ...

Is there a way to check if a date of birth is valid using Regular Expression (RegExp) within a react form?

const dateRegex = new RegExp('/^(0[1-9]|1[012])[- /.](0[1-9]|[12][0-9]|3[01])[- /.] (19|20)\d\d+$/') if (!formData.dob || !dateRegex.test(formData.dob)) { formErrors.dob = "date of birth is required" ...

Retrieve select options only upon clicking

Essentially, I have a default value that needs to be loaded into a select element and then make an API call to load the rest only when the select is clicked. <select (click)="getSubevents(market_uri)"> <option *ngFor="let subeven ...

What is the best way to preserve all props while typing a styled component in Typescript?

I'm just starting out with styled components and I want to ensure that I can properly type my styled components so that I can easily utilize all the props I pass, not just the ones defined in the theme or through an interface. Is there a way to achie ...

Avoiding memory leaks in Angular2+ when using Subscribers and subscribe.first() can be challenging

Currently, I am enhancing the performance of an Angular2 app that runs on electron. My main goal is to reduce memory leaks in the application. I know that it is crucial to unsubscribe from observables when the app is destroyed to avoid them continually l ...

There is an issue with the navigation keys not functioning correctly within the cellrenderer input boxes in ag grid

Struggling with an autocomplete input box within the cell renderer component in an ag grid cell. When attempting to use the left/right navigation keys, the input does not move inside the box and instead exits the cell abruptly. Similarly, navigating down ...

Organize multiline string based on regex pattern using Javascript

I need to split a multi-line string and group it by a specific regex pattern that repeats throughout the text Some random filler in the beginning of the content Checking against xyz... Text goes here More text and more. Checking against abc... Another se ...

TypeScript Angular Forms: Implementing correct typing for dynamic form fields

I have a formgroup that looks like this: this.formBuilder.group<{ id: number; nameDe?: FormControl<string>; nameFr?: FormControl<string>; nameIt?: FormControl<string>; }>({ id: value?.id || null }); The main foc ...