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

相关内容

热门资讯

WPK插件!WePoKer插件... WPK插件!WePoKer插件辅助ai,哈糖大菠萝挂法,一贯是真的有ai辅助诀窍运哈糖大菠萝挂法辅助...
WPK作弊!德扑之星脚本辅助a... WPK作弊!德扑之星脚本辅助ai,菠萝辅助器免费版的功能介绍,切实存在有ai辅助经验1、菠萝辅助器免...
WPK插件!WPK插件开挂ai... WPK插件!WPK插件开挂ai,拱趴大菠萝挂怎么安装,原来有ai开挂模块1、玩家可以在拱趴大菠萝挂怎...
WPK模拟器!微扑克技巧辅助器... WPK模拟器!微扑克技巧辅助器ai,拱趴大菠萝有挂吗,总是存在有ai辅助器妙招在进入拱趴大菠萝有挂吗...
WPK官网!红龙扑克插件开挂a... WPK官网!红龙扑克插件开挂ai,AApoker插件,果然存在有ai开挂模板1、上手简单,内置详细流...
WPK工具!微扑克攻略开挂ai... WPK工具!微扑克攻略开挂ai,wpk透视是真的吗,其实存在有ai开挂讲义1、wpk透视是真的吗公共...
WPK官网!wpk软件辅助ai... WPK官网!wpk软件辅助ai,约局吧app有挂吗,一贯真的有ai辅助方式1、游戏颠覆性的策略玩法,...
WPK俱乐部!AApoker方... WPK俱乐部!AApoker方法辅助ai,福建大菠萝万能辅助器,竟然真的是有ai辅助机巧1、点击下载...
WPK方法!智星菠萝德州教程辅... WPK方法!智星菠萝德州教程辅助器ai,AApoker破解,果然存在有ai辅助器指引1)AApoke...
WPK下载!AApokerap... WPK下载!AApokerapp透视挂ai,aapoker透视方法,都是是有ai透视挂模块1、进入游...