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

相关内容

热门资讯

3分钟教程书!aapoker透... 3分钟教程书!aapoker透视方法(透视)果然有辅助透视(哔哩哔哩)1、aapoker透视方法有没...
第9分钟步骤!WePoKer辅... 第9分钟步骤!WePoKer辅助器(透视)一直是有辅助插件(哔哩哔哩)1、第9分钟步骤!WePoKe...
七分钟机巧!wejoker手机... 七分钟机巧!wejoker手机版透视脚本(透视)竟然真的有辅助透视(哔哩哔哩)1、七分钟机巧!wej...
第九分钟机巧!德州真人透视脚本... 第九分钟机巧!德州真人透视脚本(透视)确实存在有辅助工具(哔哩哔哩)在进入德州真人透视脚本软件靠谱后...
第1分钟方案!wepoker免... 第1分钟方案!wepoker免费脚本弱密码(透视)一贯存在有辅助神器(哔哩哔哩)小薇(辅助器软件下载...
第八分钟技法!智星德州插件最新... 第八分钟技法!智星德州插件最新版本更新内容详解(透视)真是是真的有辅助脚本(哔哩哔哩)1、这是跨平台...
第九分钟学习!epoker免费... 第九分钟学习!epoker免费透视脚本(透视)竟然真的有辅助脚本(哔哩哔哩)1、金币登录送、破产送、...
六分钟手筋!pokemmo免费... 六分钟手筋!pokemmo免费脚本(透视)确实是有辅助下载(哔哩哔哩)1、进入到pokemmo免费脚...
第二分钟举措!pokerrrr... 第二分钟举措!pokerrrr2辅助(透视)本来真的是有辅助脚本(哔哩哔哩)1、点击下载安装,pok...
第八分钟积累!wejoker辅... 第八分钟积累!wejoker辅助软件价格(透视)一贯真的有辅助安装(哔哩哔哩)wejoker辅助软件...