Angular:在路由变更时查找内存泄漏

问题描述 投票:0回答:0

我想实现一个在路由变化时检测内存泄漏的功能。

有了这个片段。

const getMemory = () => (window.performance as any).memory.usedJSHeapSize / (window.performance as any).memory.jsHeapSizeLimit;

我的想法是,我检索当前的内存使用情况,在 NavigationStart 并将其与 NavigationEnd,不同的是内存泄漏。

目标是发现一些东西,如取消订阅。

一个例子。

import { Component } from '@angular/core';
import { Router, NavigationStart, NavigationEnd, NavigationCancel, NavigationError } from '@angular/router';

@Component({
  selector: 'my-app',
  template: `
  <div class="container">
    <a routerLinkActive="active" routerLink="/login">Login</a> |
    <a routerLinkActive="active" routerLink="/home">Home</a> | 
    <a routerLinkActive="active" routerLink="/catalog">Catalog</a> 
    <router-outlet></router-outlet>
  </div>
  `,
})
export class AppComponent  {

  private memoryStart = 0;

  constructor(private router: Router){

        const getMemory = () => (window.performance as any).memory.usedJSHeapSize / (window.performance as any).memory.jsHeapSizeLimit;

        this.router.events.subscribe((event: any) => {
          switch (true) {
            case event instanceof NavigationStart: {
              this.memoryStart = getMemory();
              break;
            }
            case event instanceof NavigationEnd: {
              console.log('Memory leak', (getMemory() - this.memoryStart));
              break;
            }
            case event instanceof NavigationCancel:
            case event instanceof NavigationError: {
              break;
            }
            default: {
              break;
            }
          }
        });
  }
}

我的想法是否正确?

javascript angular
© www.soinside.com 2019 - 2024. All rights reserved.