Angular可复用路由器变更观察者
创始人
2024-10-27 19:33:43
0

以下是一个示例解决方法,展示了如何创建一个可复用的路由器变更观察者:

  1. 创建一个名为RouterChangeObserverService的服务:
import { Injectable } from '@angular/core';
import { Router, NavigationEnd } from '@angular/router';
import { Observable, Subject } from 'rxjs';

@Injectable({
  providedIn: 'root'
})
export class RouterChangeObserverService {
  private routerChangeSubject: Subject;

  constructor(private router: Router) {
    this.routerChangeSubject = new Subject();
  }

  observeRouterChanges(): Observable {
    return this.routerChangeSubject.asObservable();
  }

  startObservingRouterChanges(): void {
    this.router.events.subscribe(event => {
      if (event instanceof NavigationEnd) {
        this.routerChangeSubject.next(event);
      }
    });
  }
}
  1. 在需要使用路由器变更观察者的组件中,注入RouterChangeObserverService并使用observeRouterChanges()方法来订阅路由器变更事件:
import { Component, OnInit } from '@angular/core';
import { RouterChangeObserverService } from '路径/到/RouterChangeObserverService';

@Component({
  selector: 'app-my-component',
  templateUrl: './my-component.component.html',
  styleUrls: ['./my-component.component.css']
})
export class MyComponentComponent implements OnInit {
  constructor(private routerChangeObserver: RouterChangeObserverService) { }

  ngOnInit(): void {
    this.routerChangeObserver.observeRouterChanges().subscribe(event => {
      // 处理路由器变更事件
      console.log('路由器变更:', event);
    });
  }
}
  1. 在需要触发路由器变更事件的地方,注入RouterChangeObserverService并调用startObservingRouterChanges()方法来开始监听路由器变更事件:
import { Component, OnInit } from '@angular/core';
import { RouterChangeObserverService } from '路径/到/RouterChangeObserverService';

@Component({
  selector: 'app-another-component',
  templateUrl: './another-component.component.html',
  styleUrls: ['./another-component.component.css']
})
export class AnotherComponentComponent implements OnInit {
  constructor(private routerChangeObserver: RouterChangeObserverService) { }

  ngOnInit(): void {
    // 触发路由器变更事件
    this.routerChangeObserver.startObservingRouterChanges();
  }
}

这样,MyComponentComponent组件就可以订阅并处理路由器变更事件,而AnotherComponentComponent组件可以触发路由器变更事件。

相关内容

热门资讯

有玩家发现!newpoker脚... 有玩家发现!newpoker脚本(透视)原来真的有挂(有挂解惑开挂辅助辅助器)-哔哩哔哩1、首先打开...
记者获悉!wepoker怎么看... 您好,wepoker怎么看底牌这款游戏可以开挂的,确实是有挂的,需要了解加去威信【485275054...
昨日!wepoker透视脚本(... 昨日!wepoker透视脚本(透视)其实确实有挂(真实有挂开挂辅助工具)-哔哩哔哩1、在wepoke...
为切实保障!wepoker透视... 为切实保障!wepoker透视有吗,pokerrrr2辅助,方针教程(有挂技术)-哔哩哔哩1、起透看...
为了进一步!hhpoker怎么... 为了进一步!hhpoker怎么破解(透视)原来是有挂(有挂方针开挂辅助下载)-哔哩哔哩1、完成hhp...
近日!智星菠萝透视,智星菠萝透... 近日!智星菠萝透视,智星菠萝透视,模板教程(有挂透明挂)-哔哩哔哩1、全新机制【智星菠萝透视软件透明...
截至目前!wepoker免费脚... 截至目前!wepoker免费脚本咨询(透视)原来有挂(有挂秘笈开挂辅助平台)-哔哩哔哩1、任何wep...
有了最新消息!xpoker辅助... 有了最新消息!xpoker辅助神器,wepoker怎么发冤家牌,策略教程(有挂教程)-哔哩哔哩1、在...
据通报!wpk模拟器(透视)其... 据通报!wpk模拟器(透视)其实是有挂(有挂分享开挂辅助插件)-哔哩哔哩wpk模拟器辅助器中分为三种...
长期以来!拱趴大菠萝万能挂图解... 长期以来!拱趴大菠萝万能挂图解,steampokermaster辅助,方针教程(有挂规律)-哔哩哔哩...