首页 > 解决方案 > Angular:在路线更改时发现内存泄漏

问题描述

我想实现一个功能来检测路由更改时的内存泄漏。

有了这个片段:

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;
            }
          }
        });
  }
}

我的想法正确吗?

标签: javascriptangular

解决方案


推荐阅读