Home > other >  I tried to do unsubscribe from an observable in angular But I am getting error like unsubscribe does
I tried to do unsubscribe from an observable in angular But I am getting error like unsubscribe does

Time:12-17

Below is the code for one of components.ts in angular and I am getting below erro Compiled with problems:X

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()
}

}

CodePudding user response:

The subscribe() method returns a Subsciption, you have to unsubscribe. To make it more useful, you should store it and unsubscribe this subscription in ngOnDestroy:

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();
  }

CodePudding user response:

An observable doesn't have unsubscribe method. When you subscribe to an observable, it gives you a subscription. Then you can unsubscribe a subscription.

const mySubscription = out$().subscribe(
  data => console.log(data)
);
mySubscription.unsubscribe();
  • Related