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辅助器,哈糖大菠萝有挂吗5个常用方法(一直有挂)1、起透看视 哈糖大菠萝有挂...
透视辅助!aapoker插件下... 透视辅助!aapoker插件下载(透视)发牌逻辑(其实真的有挂)1、点击下载安装,aapoker插件...
透视教程!poker红龙辅助,... 透视教程!poker红龙辅助,epoker底牌透视(果然真的有挂)1、让任何用户在无需epoker底...
透视ai代打!aapoker怎... 透视ai代打!aapoker怎么拿好牌(透视)透视脚本下载(都是真的是有挂);1、透视ai代打!aa...
透视安卓版!智星德州插件,智星... 透视安卓版!智星德州插件,智星德州插件最新版本更新内容详解(确实是真的有挂)1、智星德州插件最新版本...
透视插件!aapoker怎么选... 透视插件!aapoker怎么选牌(透视)免费透视脚本(都是是有挂)1、aapoker怎么选牌ai辅助...
透视最新!拱趴大菠萝万能挂图解... 透视最新!拱趴大菠萝万能挂图解,大菠萝789辅助器下载(确实是有挂)1、每一步都需要思考,不同水平的...
透视ai代打!aapoker辅... 透视ai代打!aapoker辅助插件工具(透视)插件下载(总是真的是有挂);1、aapoker辅助插...
透视数据!werplan透视挂... 透视数据!werplan透视挂,wepoker安装教程(确实是有挂);1、进入游戏-大厅左侧-新手福...
透视最新!aapoker辅助器... 透视最新!aapoker辅助器是真的吗(透视)真的假的(一贯有挂)1、游戏颠覆性的策略玩法,独创攻略...