以下是一个示例解决方法,展示了如何创建一个可复用的路由器变更观察者:
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);
}
});
}
}
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);
});
}
}
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
组件可以触发路由器变更事件。