Home > Enterprise >  Requirement to unsubscribe when outside constructor
Requirement to unsubscribe when outside constructor

Time:02-15

Quick question, would I need to unsubscribe the subscription contained here since it's not in the constructor?

import { Component, OnInit } from '@angular/core';
import { HttpService } from "./services/http.service";
import { Main } from "./interfaces/data-interface";

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss']
})
export class AppComponent implements OnInit {
  constructor(private httpService: HttpService) {
  }

  mainData: Main;
  itemIndexFocus: number = 0;


  ngOnInit() {

    this.httpService.getFighterDetail()

            .subscribe((res) => {

              this.mainData = res.body;

              console.log(this.mainData);
               
            });
  }


  getImage() {
    return this.mainData.matches[this.itemIndexFocus].image;
  }
}

The httpservice file looks like this:

import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders } from "@angular/common/http";
import { Observable } from 'rxjs';

@Injectable()
export class HttpService {

    constructor(private http: HttpClient) { }

    getFighterDetail(): Observable<any> {
        return this.http.get("/MYAPI", { responseType: 'json', observe: 'response' })
    }


}

CodePudding user response:

No you don't.

HttpClient is ‘fire once' and it automatically unsubscribes after that.

As your service wraps HttpClient you don't need to unsubscribe either.

Note it's nothing do so with whether it is declared in the constructor or not, rather amor the characteristics of the underlying observable.

CodePudding user response:

You don't have to unsubscribe from observables that completes automatically (e.g Http, calls).

But in some case you'll have to do so. No you don't need to do it to avoid memory leaks but some time you need it for avoid unwanted side effects. (you can read more here)

You can find below the best way to unsubscribe all subscription on a component destroy event.

// add this property to the compoent
private ngUnsubscribe = new Subject();

// add this pipe operator to all subscription you want to unsubscribe
.pipe(takeUntil(this.ngUnsubscribe))


// then just complete the unsubscribe subject on destroy
ngOnDestroy() {
    this.ngUnsubscribe.next();
    this.ngUnsubscribe.complete();
}
  • Related