1
  public testArr: any = []; 
     getData() {
        this.dataS.getSensor().subscribe((data: any) => {
            this.testArr= data; 
        })
      }


this.testArr.unsubscribe()

How if my testArr is array ? Now is older then now?

acaaca19993
  • 33
  • 1
  • 7

6 Answers6

5

You can only unsubcribe from an Observable, which is not the case with testArr.

// declare a subscription
subscription: Subscription = new Subscription();

getData() {
// reference your observable to the subscription
  this.subscription = this.dataS.getSensor().subscribe((data: any) => {
    this.testArr= data; 
      })
    }

// unsubscribe when the component gets destroyed
ngOnDestroy() {
  this.subscirption.unsubscribe();  
}
Wai Ha Lee
  • 8,598
  • 83
  • 57
  • 92
Gérôme Grignon
  • 3,859
  • 1
  • 6
  • 18
1

Multiple Subscription variables can get out of hand very quick and can be messy.

A better approach would be to use a subject, this can be reused for every subscription as follows.

// Declare a subscription handler
private onDestroy$ = new Subject();

getData() {
    // here we will use the onDestroy$ Subject to automatically unsubscribe
    this.dataS.getSensor()
    .pipe(takeUntil(this.onDestroy$))
    .subscribe((data: any) => {
        this.testArr= data; 
    });
}

// complete the subject when the component gets destroyed to unsubscribe
ngOnDestroy() {
    this.onDestroy$.next();
    this.onDestroy$.complete();
}

With the latest angular, subscriptions using http are handled and cleaned up automatically, but it is in some scenarios it's still best practice to unsubscribe yourself as well.

Jayme
  • 1,776
  • 10
  • 28
Stephen
  • 47
  • 6
  • This is my preferred method to unsubscribe because you can unsubscribe from a single variable, in this case 'onDestroy$', and everything making use of it will get unsubscribed too – Jayme Oct 22 '21 at 10:21
0

You could also use async pipe that unsubscribes automatically. https://angular.io/api/common/AsyncPipe

component.ts

 // use your type instead of any
 data$: Observable<any>;

 ngOnInit() {
   this.data$ = this.dataS.getSensor();
 }

template.ts

<div *ngIf="data$ | async as data">
  // now you can use data property as you want
</div>
akushylun
  • 151
  • 1
  • 5
0

The normal way is: to define a subscription variable, assign the susbscribe result and unsubscribe on detroy method (of componnet).

@Component({ .... })
export class AppComponent implements OnInit, OnDestroy {  
  
  private subscription: Subscription = new Subscription();
  public testArr: any = []; 
  
  getData() {
        this.subscription =
          this.dataS.getSensor().subscribe((data: any) => {
            this.testArr= data; 
            })
      }


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

A variant to the above is to use the Add method.

this.subscription.Add ( this.dataS.getSensor().subscribe(...) );
this.subscription.Add ( this.Observable2.subscribe(...) );
this.subscription.Add ( this.Observable3.subscribe(...) );

and finally:

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

This allows to manage multiple susbcription in one subscription variable

On the other hand, there is an alternative that I have been experimenting with and it has worked for me:

@Component({ .... })
export class AppComponent implements OnInit, OnDestroy {  
  
  private subscription: Subscription = new Subscription();
  public testArr: any = []; 
  
  //Define an POO "old school" event
  private onDataArrive?: () => void
  
  ngOnInit() {
      //Assign the event, with unsubscribe method.
      this.onDataArrive = () =>
        {
          //unsubscribe
          this.subscription.unsubscribe();
        }
  }
  
  getData() {
        //Assign the subscription 
        this.subscription =
          this.dataS.getSensor().subscribe((data: any) => {
            this.testArr= data; 
            
            //if event is assigned, then call it
            if (this.onDataArrive) this.onDataArrive();
            
            })
      }

}  

looks, a lite bit "more complex" than just unsubscribe at the onDestroy method... but, an observable is a thread listening permanently and this way can unsubscribe it as soon as response arrive, and not wait until the end of component life.

GatoSoft
  • 106
  • 1
  • 3
0

There are below 5 ways to unsubscribe a component in angular, after it uses.

  • By Using unsubscribe() method with ngOnDestroy() lifehooks.
  • By Using Async pipe.
  • By using RxJs take* operator
  • By Creating a custom decorator.
  • By using TS lint. Please see the below link more about unsubscribing an Angular component 5-ways-to-unsubscribe-an-angular-component
0

If you are using angular HttpClient there is no need to unsubscribe.

httpClient sends only one value and then complete.

Otherwise you can user a decoator that will unsubscribe from all observables when the component is destroyed https://github.com/NetanelBasal/ngx-auto-unsubscribe

@AutoUnsubscribe()
@Component({
 selector: 'app'
})

No Need of unsubscribe in these cases

  • In case of HttpClient calls because the observable emit one value (success or error) and complete automatically.
  • In case or ActivatedRoute subscription because the Router will destroy it when the component is destroyed automatically
  • use of Async pipe
Fateh Mohamed
  • 20,445
  • 5
  • 43
  • 52