[Angular2 Router] Exiting an Angular 2 Route - How To Prevent Memory Leaks

In this tutorial we are going to learn how we can accidentally creating memory leaks in our application while using the Angular 2 router. We are going to learn how we can prove that the memory leak is happening, we are going to learn what is causing it and how we can fix it.

This is an issue that might become visible in very large applications which load a lot of data from the backend, and might cause errors that can be very hard to troubleshoot.

 

复制代码
import {Component, OnInit, OnDestroy} from '@angular/core';
import {ActivatedRoute, RouterStateSnapshot, Router} from "@angular/router";
import {StarWarsService} from "../heros.service";
import {Observable, Subscription} from "rxjs";

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

  hero: Observable<any>;
  description: string;
  querySub: Subscription;

  constructor(private route: ActivatedRoute,
              private router: Router,
              private starwarService: StarWarsService) {

  }

  ngOnInit() {
    /* this.hero = this.router.params
     .map((p:any) => p.id)
     .switchMap( id => this.starwarService.getPersonDetail(id));
     */

    // since herocomponent get init everytime, it would be better to use snapshot for proferemence
    const heroId = this.route.snapshot.params['id'];
    this.hero = this.starwarService.getPersonDetail(heroId);

    this.querySub = this.route.queryParams.subscribe(
      param => this.description = param['description']
    );

    console.log("observers", this.route.queryParams['observers'].length)
  }

  ngOnDestroy(){
    this.querySub.unsubscribe()
  }

}
复制代码

 

Github

posted @   Zhentiw  阅读(300)  评论(0编辑  收藏  举报
编辑推荐:
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具
点击右上角即可分享
微信分享提示