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

相关内容

热门资讯

透视辅助!aapoker怎么开... 透视辅助!aapoker怎么开辅助器,素来存在有挂(透视)教你攻略(有挂方法)1、任何aapoker...
透视玄学!hhpoker真的假... 透视玄学!hhpoker真的假的,起初是有挂(透视)黑科技教程(有挂攻略)1、完成hhpoker真的...
透视辅助!aapoker如何设... 透视辅助!aapoker如何设置胜率,本来是真的有挂(透视)力荐教程(有挂插件)1、上手简单,内置详...
透视中牌率!wepoker辅助... 透视中牌率!wepoker辅助工具,果然是有挂(透视)曝光教程(有挂教程)1、金币登录送、破产送、升...
透视中牌率!newpoker怎... 透视中牌率!newpoker怎么安装脚本,切实真的是有挂(透视)安装教程(有挂解说)暗藏猫腻,小编详...
透视存在!德普之星辅助器怎么用... 透视存在!德普之星辅助器怎么用,竟然真的有挂(透视)安装教程(有挂脚本);1、每一步都需要思考,不同...
透视代打!约局吧如何查看是否有... 透视代打!约局吧如何查看是否有挂,果然真的是有挂(透视)玩家教你(有挂脚本)1、用户打开应用后不用登...
透视模拟器!wepoker辅助... 透视模拟器!wepoker辅助器免费,确实真的是有挂(透视)2025新版总结(有挂解说)所有人都在同...
透视脚本!wepoker免费透... 透视脚本!wepoker免费透视脚本,从来有挂(透视)玩家教程(有挂教程)1、下载好wepoker免...
透视挂!wepoker怎么发冤... 透视挂!wepoker怎么发冤家牌,其实是有挂(透视)扑克教程(有挂辅助)1、下载好wepoker怎...