"Discovering the root cause of Angular memory leaks and resolving them effectively is crucial for

I am facing an issue with a code that appears to be leaking, and I am seeking advice on how to identify the cause or properly unsubscribe. Even after adding an array containing all object subscriptions, the memory leakage persists.

import { Component, OnInit } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { of } from 'rxjs';
import { delay, tap, mergeMap, repeat } from 'rxjs/operators';

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

  postId;
  
  callOmni = () => of(this.pollOmni()).pipe();
  display = response => {};
  poll = of({}).pipe(
  mergeMap(_ => this.callOmni()),
  tap(this.display),
  delay(10),
  repeat()
);

  constructor(private http: HttpClient) { } 
  pollOmni() {      
    // Simple POST request with a JSON body and response type <any>
    this.http.post<any>('http://127.0.0.1:8084/api', { call: 'getinfo' }).subscribe(
      data => {
        this.postId = data;
        console.log(this.postId);
        }),
        error => {
          console.log('oops', error)
        }
     
   
  }

  ngOnInit() {      
    // Simple POST request with a JSON body and response type <any>
   
    this.poll.subscribe();
  }

}

Answer №1

Your code appears to have a subscription issue within the pollOmni() method, leading to multiple active subscriptions that can cause memory leaks if not unsubscribed properly.

To resolve this issue, ensure you unsubscribe from the subscription when no longer needed. One approach is to store the subscription in a variable and unsubscribe as necessary.

Below is an updated version of your code with the necessary modifications implemented:

import { Component, OnInit, OnDestroy } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { of, Subject } from 'rxjs';
import { delay, tap, mergeMap, repeat, takeUntil } from 'rxjs/operators';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit, OnDestroy {
  postId;
  private ngUnsubscribe = new Subject<void>(); // Subject for unsubscribing

  constructor(private http: HttpClient) { }

  callOmni = () => of(this.pollOmni()).pipe();

  display = response => {
    // Display logic here
  };

  poll = of({}).pipe(
    mergeMap(_ => this.callOmni()),
    tap(this.display),
    delay(10),
    repeat(),
    takeUntil(this.ngUnsubscribe) // Unsubscribe when ngUnsubscribe emits
  );

  pollOmni() {
    return this.http.post<any>('http://127.0.0.1:8084/api', { call: 'getinfo' });
  }

  ngOnInit() {
    this.poll.subscribe();
  }

  ngOnDestroy() {
    this.ngUnsubscribe.next(); // Emit value to unsubscribe from ongoing subscriptions
    this.ngUnsubscribe.complete(); // Complete the subject
  }
}

Answer №2

Here is an example:

class ExampleComponent implements OnChanges, AfterViewInit {
  ...

  ngAfterViewInit(): void {
    this.subscription.unsubscribe();
  }
}

Answer №3

Ensure your code includes the OnDestroy Life cycle hook in Angular and properly unsubscribe within the ngOnDestroy method as shown below:

import { Component, OnInit, OnDestroy } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { of } from 'rxjs';
import { delay, tap, mergeMap, repeat } from 'rxjs/operators';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit, OnDestroy {

  postId;
  private unsubscribe = new Subject<void>();
  callOmni = () => of(this.pollOmni()).pipe();
  display = response => {};
  poll = of({}).pipe(
    mergeMap(_ => this.callOmni()),
    tap(this.display),
    delay(10),
    repeat(),
    takeUntil(this.unsubscribe)
);

constructor(private http: HttpClient) { } 
pollOmni() {      
    
    this.http.post<any>('http://127.0.0.1:8084/api', { call: 'getinfo' }).subscribe(
      data => {
        this.postId = data;
        console.log(this.postId);
        }),
        error => {
          console.log('oops', error)
        }
     
   
  }

  ngOnInit() {      
    this.poll.subscribe();
  }

ngOnDestroy(): void {
    this.unsubscribe.next(); 
   this.unsubscribe.complete();
  }
}

If the above solution does not meet your requirements, consider utilizing the template mechanism in Angular using the Angular Async Pipe. Please see the sample implementation below demonstrating the usage of pipes in Angular.

@Component({
      selector: 'app-stock',
      template: `
        <div *ngIf="stocks$ | async as stocks">
          <ul>
            <li *ngFor="let stock of stocks">
              {{ stock.symbol }}
            </li>
          </ul>
        </div>
      `,
      styleUrls: ['./stock.component.scss'],
    })
    export class StockComponent implements OnInit {
      stocks$: Observable<Stock[]> = this.stockService.getStocks();
    
      constructor(private stockService: StockService) {}
    
      ngOnInit(): void {}
    }

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

The CORS preflight request for OPTIONS method is returning a 401 (Unauthorized) response from a Windows Authenticated web API

I am facing an issue with my .NET Web API project that uses Windows Authentication. In my development environment, I am unable to make a successful POST request with data from my Angular app. The error message I receive is: OPTIONS http://localhost:9090/a ...

I require all of this to be brought back as one complete entity. If, for instance, the object is given the value 10/26, it should be interpreted as part of the input

I am facing an issue with my Angular + .NET Application where the search method is not recognizing a specific ConsumerUnit when the input includes a / character. Currently, if I input something like 10/2689123, the application treats the / as part of the ...

Switching class on a specific element in Angular 2

My element list appears like this: <ul *ngFor="let period of periodsDate"> <li [class.show]="isShown" (click)="toggleClass()"> <a>{{ period.id }} </a> </li> </ul> ...

The Angular error TS2531 occurs when attempting to call scrollIntoView on an object that may be null

In my current Angular project, I am attempting to implement a scroll view using ViewChild by id. This is the method I have written: ngOnInit() { setTimeout(() => { if (this.router.url.includes('contact')) { ...

Using Angular and Firestore to push matched properties into an array

Module 1 this.service.myArray['bands'] = data; Module 2 Module two is designed to receive artist IDs individually through an @Input attribute. Following that, a query is executed to retrieve all relevant albums. Each album entry includes an &ap ...

Angular web application can retrieve JSON data from a web API controller, allowing for

I'm currently utilizing ASP.NET Core on the backend and Angular on the frontend. My API delivers data in JSON format from the backend. I've set up a service to fetch the API data, but it's returning 'undefined' at the moment. emp ...

Updating color of an element in SVG and Angular2+ according to the background

In my svg element, I have a text element positioned after two rect elements. <svg id="floor-plan" width="300" height="100"> <rect width="300" height="100" fill="white"/> <rect width="50" height="50" fill="green"/> <text x="10" y="10" ...

Developing an npm library with ReactJs: A step-by-step guide

As a newcomer to React, I am eager to create my own npm library in ReactJS. Taking inspiration from my existing React project, the goal is to transform it into a package (or library) that can be easily integrated into other projects. This means allowing ...

Unable to start Angular application, encountering errors while running ng serve

The challenge at hand As I delve into a new project, I've successfully cloned the repository onto my local machine. After utilizing npm install to fetch the necessary packages, running ng serve triggers a series of errors. Despite the application fai ...

Transform an angular1 javascript circular queue implementation for calculating rolling averages into typescript

I am currently in the process of migrating a project from Angular 1 to Angular 2. One of the key components is a chart that displays a moving average line, which requires the use of a circular queue with prototype methods like add, remove, and getAverage. ...

How can RootStateOrAny be turned off in React with typescript?

Whenever I need to employ useSelector, I find myself repeating this pattern: const isLoading = useSelector( (state) => state.utils.isLoading ); Is there a shortcut to avoid typing out RootStateOrAny each time? It's starting to become a hassl ...

Ensure that selecting one checkbox does not automatically select the entire group of checkboxes

Here is the code I'm using to populate a list of checkboxes. <label class="checkbox-inline" ng-repeat="item in vm.ItemList track by item.id"> <input type="checkbox" name="item_{{item.id}}" ng-value="{{item.id}}" ng-model="vm.selectedItem" /& ...

Difficulty in dynamically changing Angular 6 directive attributes

I am currently working with component A, which features a custom directive on the web page: Here is how it looks: <warning [details]='details'></warning> The code for Component A is as follows: export class AComponent implemen ...

What steps should I follow to properly set up my tsconfig.json in order to ensure that only the essential files are included when executing npm run build

Introduction I am seeking guidance on how to correctly set up my tsconfig.json file to ensure only the necessary files are included when running npm run build for my projects. I want to avoid any unnecessary files being imported. Query What steps should ...

Active Class in Angular Dynamic Carousel

I recently set up a dynamic carousel that pulls images directly from a node backend. While everything seems to be in working order, I've run into an issue where all the images are being displayed at once instead of sliding through one at a time. This ...

Why is the CanDeactivate Guard unable to access a function within my component?

My routes are being loaded lazily and I am facing an issue with the CanDeactivate guard not being able to access the component's properties or methods as required by the documentation. Below is the implementation of my guard: @Injectable() export cl ...

The issue with Angular 2's Parameterised router link component not fully refreshing

I'm trying to figure out how to show a set of images when I click on a specific menu item. The menu structure looks like this: <ul id="demo23" class="collapse"> <li> <a [routerLink]="['image-gallery','Picasso ...

Utilizing Ionic to import and parse an Excel file for data processing

I need assistance in uploading an Excel file and reading it using Ionic-Angular. I tried the following code, but it only seems to work for browsers and not for the Ionic app on Android. Can someone please help me with this issue? I am trying to read the E ...

Guide on incorporating Paddle into your SvelteKit project

I'm struggling to implement a Paddle Inline Checkout in SvelteKit. Every time I try, I keep encountering the error message Name Paddle not found. It seems like the script is not functioning properly. Console Error: Uncaught (in promise) ReferenceErro ...

Error: The Angular2 Router is unable to locate the XOutlet outlet in order to load the YComponent

I've encountered an issue while using named router outlets in Angular2 version 2.1.2. The error message I'm receiving is: Cannot find the outlet XOutlet to load 'YComponent' Although the error message is clear, I'm struggling ...