AngularNgoninit每次路由时都会被调用
创始人
2024-10-28 17:01:15
0

使用RxJS的takeUntil操作符将订阅取消时机与路由导航关联起来,以便在组件销毁前取消未完成的订阅。

示例代码:

import { Component, OnInit, OnDestroy } from '@angular/core'; import { takeUntil } from 'rxjs/operators'; import { Subject } from 'rxjs'; import { Router, NavigationEnd } from '@angular/router';

@Component({ selector: 'app-my-component', templateUrl: './my-component.component.html', styleUrls: ['./my-component.component.css'] }) export class MyComponentComponent implements OnInit, OnDestroy { private ngUnsubscribe = new Subject();

constructor(private router: Router) { }

ngOnInit() { this.router.events .pipe(takeUntil(this.ngUnsubscribe)) .subscribe(event => { if (event instanceof NavigationEnd) { // 在这里编写处理导航结束时要做的事情 } }); }

ngOnDestroy() { this.ngUnsubscribe.next(); this.ngUnsubscribe.complete(); } }

在组件的ngOnInit方法中,使用takeUntil操作符将路由事件与ngUnsubscribe主体关联起来,以便在组件销毁之前取消任何未完成的订阅。在这个例子中,我们只关心NavigationEnd事件。在组件的ngOnDestroy方法中,我们取消与ngUnsubscribe相关的所有订阅。

相关内容

热门资讯

总结透视!pokemmo手机脚... 总结透视!pokemmo手机脚本辅助器,wepoker怎么增加运气,方式教程(有挂助手)-哔哩哔哩;...
解密透视!约局吧德州可以透视吗... 解密透视!约局吧德州可以透视吗!确实真的是有辅助工具(有挂讲解)-哔哩哔哩亲,关键说明,约局吧德州可...
普及透视!we-poker辅助... 普及透视!we-poker辅助软件教程,aapoker能控制牌吗,模块教程(有挂攻略)-哔哩哔哩1、...
科普透视!pokemomo辅助... 科普透视!pokemomo辅助软件!好像存在有辅助神器(讲解有挂)-哔哩哔哩1、pokemomo辅助...
专业透视!wpk插件,wepo... 专业透视!wpk插件,wepoker透视挂底牌,法子教程(有挂教学)-哔哩哔哩1、完成wepoker...
教你透视!福建大菠萝万能辅助器... 教你透视!福建大菠萝万能辅助器!好像有辅助工具(有挂详细)-哔哩哔哩1、上手简单,内置详细流程视频教...
解迷透视!哈糖大菠萝有挂吗5个... 解迷透视!哈糖大菠萝有挂吗5个常用方法,wepoker看底牌,指引教程(有挂规律)-哔哩哔哩1、解迷...
有挂透视!拱趴大菠萝挂!一直是... 有挂透视!拱趴大菠萝挂!一直是真的有辅助脚本(确实有挂)-哔哩哔哩一、拱趴大菠萝挂可以开透视的定义与...
必备透视!pokemmo脚本辅... 必备透视!pokemmo脚本辅助,hhpoker德州透视挂,法子教程(有挂透视)-哔哩哔哩1、该软件...
揭露透视!pokerworld... 揭露透视!pokerworld辅助器!总是是有辅助软件(详细教程)-哔哩哔哩1、用户打开应用后不用登...