Categories
Javascript

Do We Need to Unsubscribe Angular HttpClient?

Is there any way we can unsubscribe Angular HttpClient manually? Fortunately, yes we have! But we don’t need to unsubscribe it. Instead, HttpClient observes until getting a response from API. And, once it gets the response, HttpClient unsubscribes automatically.

Https use AsyncPipe for the response and the AsyncPipe subscribes to an Observable. It returns the latest value it has emitted. When a new value is found, the AsyncPipe observes for any change. The checking continues until the set of code become false. Once the component gets destroyed, the AsyncPipe unsubscribes automatically to avoid potential memory leaks.

import {Injectable} from '@angular/core';
import {HttpClient, HttpParams} from '@angular/common/http';

@Injectable({
    providedIn: 'root'
})
export class ApiService {

    constructor(private http: HttpClient) {
    }
    post(endpoint: string, body: any, reqOpts?: any) {
        return this.http.post(this.url + '?' + endpoint, body, reqOpts);
    }
}

const seq = this.api.post(endpoint, body);
    seq.subscribe((res: any) => {
       console.log(res)
    }, (error) => {
      console.log(error)
    },
    () => {
   console.log('complete');
});

Validate the above-mentioned set of codes to get rid of the problem you face in Angular HttpClient.