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

相关内容

热门资讯

透视法子!大菠萝手游辅助(WP... 透视法子!大菠萝手游辅助(WPK透视)本来真的是有辅助方法(哔哩哔哩)1、许多玩家不知道大菠萝手游辅...
透视手册!德普之星透视免费(W... 透视手册!德普之星透视免费(WePoKer祈福)一贯真的是有辅助工具(哔哩哔哩)1、德普之星透视免费...
透视窍门!wepoker透视挂... 透视窍门!wepoker透视挂底牌(WePoKer高级)一直真的有辅助脚本(哔哩哔哩)1、wepok...
透视指南!红龙poker辅助(... 透视指南!红龙poker辅助(HHpoker模拟器)竟然存在有辅助神器(哔哩哔哩)1、下载好红龙po...
透视经验!hhpoker有没有... 透视经验!hhpoker有没有外开挂(WePoKer辅助挂)总是真的有辅助教程(哔哩哔哩)1、hhp...
透视诀窍!wpk俱乐部是真的吗... 透视诀窍!wpk俱乐部是真的吗(WPK安装)一贯是有辅助方法(哔哩哔哩)1、上手简单,内置详细流程视...
透视练习!hhpoker是正规... 透视练习!hhpoker是正规的吗(WePoKer安卓)果然是真的有辅助方法(哔哩哔哩)1、上手简单...
透视大纲!wepoker数据分... 透视大纲!wepoker数据分析工具(HHpoker有辅助)好像真的是有辅助插件(哔哩哔哩)1、每一...
透视手段!德普之星透视辅助插件... 透视手段!德普之星透视辅助插件(WePoKer价格)真是真的有辅助插件(哔哩哔哩)1、完成德普之星透...
透视绝活!fishpoker透... 透视绝活!fishpoker透视底牌(AApoker ai)果然真的有辅助app(哔哩哔哩)1、在f...