I attempted to unsubscribe from an observable in Angular, but I encountered an error stating that the unsubscribe function does not exist

Here is the code snippet from a components.ts file in an Angular project. I encountered the following error during compilation:

ERROR

merge/merge.component.ts:75:12 - error TS2551: Property 'unsubscribe' does not exist on type 'Observable'. Did you mean 'subscribe'?

75 out$().unsubscribe() ~~~~~~~~~~~

../../node_modules/rxjs/dist/types/internal/Observable.d.ts:53:5 53 subscribe(observer?: Partial<Observer>): Subscription; ~~~~~~~~~ 'subscribe' is declared here.

import { Component, ElementRef, OnDestroy, OnInit, ViewChild } from '@angular/core';
import { defer, Observable, of, Subscription } from 'rxjs';
import { HttpClient } from '@angular/common/http';
import {filter,map,distinctUntilChanged,distinctUntilKeyChanged, mergeAll, mergeMap, concatAll, retry, repeat} from 'rxjs/operators'
import {from} from 'rxjs';

@Component({
  selector: 'app-merge',
  templateUrl: './merge.component.html',
  styleUrls: ['./merge.component.scss']
})
export class MergeComponent implements OnInit {
   public items:any[]=[];
   constructor(private http: HttpClient){}

  ngOnInit(): void {
    let counter=1;
    const out$=()=> defer(()=>this.http.get('https://jsonplaceholder.typicode.com/todos/'+counter++)).pipe(
      repeat(4)
    );
    out$().subscribe(
      data => console.log(data)
    )
    out$().unsubscribe()
}

}

Answer №1

When using the subscribe() method in Angular, it is important to remember to unsubscribe to avoid memory leaks. You can achieve this by storing the subscription and unsubscribing in the ngOnDestroy lifecycle hook:

export class MergePageComponent implements OnInit, OnDestroy {

  protected mySubscription: Subscription;
  
  constructor(  )

  ngOnInit(): void {
    ...
    this.mySubscription = out$().subscribe(
      data => console.log(data)
    );
  }

  ngOnDestroy(): void {
    this.mySubscription.unsubscribe();
  }

Answer №2

Observables do not come with an unsubscribe method. To unsubscribe from an observable, you must first subscribe to it and then use the subscription to unsubscribe.

const mySubscription = observe$().subscribe(
  info => console.log(info)
);
mySubscription.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

Issue: NullInjectorError: R3InjectorError(AuthorModule)[ScrollbarHelper -> ScrollbarHelper -> ScrollbarHelper -> ScrollbarHelper]:

While I am going through a tutorial on the abp framework, I encountered an error with the Author route that says "ERROR Error: Uncaught (in promise): NullInjectorError: R3InjectorError(AuthorModule)[ScrollbarHelper -> ScrollbarHelper -> ScrollbarHelp ...

Unable to locate any static exports within the TypeScript library bundle

In my file Style.ts, I have a class called Style: export class Style { ... } The Style class consists of properties, methods, and a constructor, along with import statements for other class dependencies. It is being used by other classes through the ...

Tips for bundling and inlining .json files within an Angular npm package

I am currently in the process of developing an NPM Package for an Angular module that I intend to utilize across several Angular applications. The Angular module I have developed relies on ng2-translate to access localization strings stored in .json file ...

Exploring Angular: A Guide to Importing Material Components

Trying to incorporate elements such as sliders and tooltips into my project, but encountering issues with imports. I've experimented with adding the import statement for MatSliderModule in various locations like app.module.ts and specific component mo ...

Issue with Angular Reactive form: Checkbox checked property not binding correctly when the page initially loads

Looking to achieve Two-way data binding of Checkbox in Angular Reactive forms. After checking the checkbox, I am updating the 'isdateChkd' variable and storing it in the state. Despite the variable being set to TRUE, the checkbox does not get aut ...

Can you provide guidance on effectively utilizing a Pinia store with Vue3, Pinia, and Typescript?

I'm currently facing challenges while using the Pinia store with TypeScript and implementing the store within a basic app.vue Vuejs3 option api. Here is my app.js file: import {createApp} from 'vue' import {createPinia} from "pinia&quo ...

The TS2345 error is triggered when using the fs.readFile function with specified string and

Attempting to utilize the fs.readFile method in TypeScript, my code looks like this... import {readFile} from 'fs'; let str = await readFile('my.file', 'utf8'); This results in the following error message: TS2345: Argumen ...

Discover the inverse of Object Arrays interaction in TypeScript

My agent object has the following structure: agentObj = { "agentId": "saqib", "attributes": [ { "name": "Marketing", "type": "Boolean", }, { "name": "English", "type": "Profi ...

What is the process of creating a typeorm relationship between orders and products?

My Orders Entity file in TypeOrm looks like this: @Entity('orders') export class OrdersEntity { @PrimaryGeneratedColumn('uuid') id: string; @CreateDateColumn() created: Date; @UpdateDateColumn() updated: Date; @Column('t ...

Enhance the display in Angular2

Just started working with Angular 2 and I've encountered a problem. I have an API that loads a JavaScript file in my project. The issue is, I need to use this JS file and cannot modify it. Essentially, this JS file has some methods that make AJAX call ...

Guidelines for automatically exporting (and downloading) a Highcharts chart created in Angular

I've been working on an Angular project where I successfully created a chart using the Highcharts library and the Angular-Highcharts package. The chart looks great, but now I'm facing an issue with automatically exporting it using the Highcharts ...

Display a modal dialog using HttpInterceptor

@Injectable() export class MyInterceptor implements HttpInterceptor { intercept(req : HttpRequest<any>, next : HttpHandler) : Observable<HttpEvent<any>> { //display a modal dialog to wait for user response before proceeding with t ...

What is the best way to configure webpack for ng build instead of ng serve?

My .NET web application is hosted in IIS and it also hosts an Angular application. This setup requires both applications to be served on the same port by IIS, primarily because they share the same session cookie. Additionally, they are integral parts of th ...

Incorporate form information into an array in Angular Version 2 or higher

This form is where I craft my questions https://i.sstatic.net/93781.png When composing a question, the ability to include multiple alternatives is available. There will also be an option to edit these alternatives. The desired format for my array is as ...

Is it possible to have routing only within child components in Angular 2?

I have set up a main component as the root component <tracker-module></tracker-module> Within the main component, there are sub-components structured like this: <header></header> <left-navigation></left-navigatio ...

Ways to specify the T (Generic type) associated with the class

I am working with a class that uses a generic type like this: SomeGenericClass<T>{ constructor(){ } } Within some of the functions, I log messages and want to refer to the current type T of the generic class in my logs. I have attempted t ...

Error thrown due to syntax issues in react.d.ts declaration file in TypeScript

Currently, I am attempting to integrate react with typescript in my project. However, typescript is generating syntax errors for the react.d.ts file sourced from Github: https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/react The encountered ...

Is there a solution for the error "Unable to persist the session" in a Next.js application that utilizes Supabase, Zustand, and Clerk.dev for authentication?

I have successfully set up a Next.js application with Clerk.dev for authentication and Supabase for data storage. I'm also leveraging Zustand for state management. However, an error is plaguing me, stating that there's "No storage option exists t ...

Dynamic Route Matching in NextJS Middleware

Currently, I am in the process of developing a website that incorporates subdomains. Each subdomain is linked to a file-based page using middleware. Take a look at how the subdomains are being mapped to specific pages: app.com corresponds to /home app.com ...

Assigning initial value to a BehaviorSubject in an Angular application

I'm still getting the hang of Rxjs. How do I go about initializing the first value of a BehaviorSubject with data from a custom select box model? Here's what the model looks like: private mainRangeDate: any = {beginDate: {year: 2018, mon ...