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

相关内容

热门资讯

外挂模板!哈糖大菠萝攻略,德普... 外挂模板!哈糖大菠萝攻略,德普之星辅助工具如何打开-本来是真的有辅助方法(哔哩哔哩)进入游戏-大厅左...
外挂办法!sohoo poke... 外挂办法!sohoo poker辅助,德普之星私人局辅助器-竟然一直都是有辅助神器(哔哩哔哩)1、s...
外挂指引!德普之星辅助器,we... 外挂指引!德普之星辅助器,werplan辅助软件-果然真的有辅助软件(哔哩哔哩)1、werplan辅...
外挂指南!云扑克有透视吗,菠萝... 外挂指南!云扑克有透视吗,菠萝辅助器免费版的功能介绍-一贯是有辅助脚本(哔哩哔哩)1、操作简单,无需...
外挂方案!pokemomo辅助... 外挂方案!pokemomo辅助工具,pokemomo辅助软件-确实一直总是有辅助插件(哔哩哔哩)1、...
外挂步骤!德州局怎么透视,线上... 外挂步骤!德州局怎么透视,线上德州的辅助器是什么-果然存在有辅助方法(哔哩哔哩)一、线上德州的辅助器...
外挂积累!红龙poker辅助工... 外挂积累!红龙poker辅助工具,红龙poker有辅助吗-其实真的有辅助app(哔哩哔哩)1、玩家可...
外挂攻略!拱趴大菠萝万能辅助器... 外挂攻略!拱趴大菠萝万能辅助器,佛手在线是不是有挂-一直存在有辅助软件(哔哩哔哩)1、拱趴大菠萝万能...
外挂学习!xpoker怎么作必... 外挂学习!xpoker怎么作必弊,德普之星辅助器怎么用-都是真的有辅助教程(哔哩哔哩)1、打开软件启...
外挂步骤!uupoker有透视... 外挂步骤!uupoker有透视吗,pokeplus脚本-一贯真的是有辅助方法(哔哩哔哩)暗藏猫腻,小...