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相关的所有订阅。

相关内容

热门资讯

我来向大家传授!wepoker... 我来向大家传授!wepoker好友局透视,pokemmo脚本辅助下载,线上教程(有挂方法);支持2-...
透视规律!竞技联盟辅助(透视)... 透视规律!竞技联盟辅助(透视)好像是有挂(详细辅助透视教程)1、这是跨平台的黑科技,在线的操作超级的...
科普!aapoker透视脚本入... 科普!aapoker透视脚本入口,wepoker透视最简单三个步骤,黑科技教程(有挂软件);建议优先...
透视好友!wepoker永久免... 透视好友!wepoker永久免费脚本(透视)其实是有挂(详细辅助辅助教程)1、进入到黑科技之后,能看...
实测必看!aapoker透视插... 实测必看!aapoker透视插件,wepoker破解器有用吗,新2025教程(有挂攻略),支持语音通...
透视真的!wepoker有透视... 透视真的!wepoker有透视底牌吗(透视)都是真的有挂(详细辅助可靠教程)1、机器人多个强度级别选...
今日重大通报!we-poker... 今日重大通报!we-poker是什么软件,aapoker辅助软件合法吗,普及教程(有挂方法)准备好在...
透视游戏!pokemmo辅助器... 透视游戏!pokemmo辅助器(透视)原来真的有挂(详细辅助揭秘教程);1、超多福利:超高返利,海量...
玩家爆料!hhpoker破解工... 玩家爆料!hhpoker破解工具,wepoker插件功能辅助器,德州教程(有挂透明)准备好在wepo...
透视肯定!德州私人局怎么透视(... 透视肯定!德州私人局怎么透视(透视)一贯真的有挂(详细辅助我来教教你)1、首先打开最新版本,在首页我...