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

相关内容

热门资讯

透视能赢!哈糖大菠萝怎么挂(透... 透视能赢!哈糖大菠萝怎么挂(透视)果然真的有挂(详细辅助第三方教程)1、金币登录送、破产送、升级送、...
教程辅助!pokerworld... 教程辅助!pokerworld修改器,wejoker辅助器怎么卖,扑克教程(有挂技巧);1.wejo...
辅助透视!佛手大菠萝有挂吗(透... 辅助透视!佛手大菠萝有挂吗(透视)原来有挂(详细辅助科技教程)辅助器中分为三种模型:软件透明挂、辅助...
一分钟揭秘!aapoker辅助... 一分钟揭秘!aapoker辅助软件合法吗,wepoker辅助器安装包,扑克教程(有挂透视);科技安装...
透视规律!智星德州插件2024... 透视规律!智星德州插件2024最新版(透视)总是真的是有挂(详细辅助扑克教程)1、用户打开应用后不用...
三分钟了解!德州hhpoker... 三分钟了解!德州hhpoker脚本,wepoker私人局透视插件,力荐教程(有挂软件);1.wepo...
透视有挂!wepoker底牌透... 透视有挂!wepoker底牌透视(透视)其实真的有挂(详细辅助力荐教程)1)辅助挂:进一步探索辅助透...
大家学习交流!wepoker私... 大家学习交流!wepoker私人局怎么玩,we poker辅助器,高科技教程(有挂技巧)1、玩家可以...
透视透视!wepoker透视有... 透视透视!wepoker透视有吗(透视)原来真的是有挂(详细辅助爆料教程);1、进入到wepoker...
重大通报!pokemmo辅助工... 1、重大通报!pokemmo辅助工具,wepoker私局辅助,科技教程(有挂辅助)。2、pokemm...