这个问题通常发生在父级模块和子级模块之间的跳转,因为Angular通常只会跟踪与当前激活的路由相关的组件。如果新的组件不在此路由下,那么激活事件就不会触发。
解决此问题的方法是使用共享服务,使父级组件通过服务接收激活路线信息并将此信息传递给子模块的组件,从而触发激活事件。
这里有一个简单的示例:
//在共享服务中定义一个Subject,用于接收激活路由信息 import { Injectable } from '@angular/core'; import { Subject } from 'rxjs';
@Injectable({
providedIn: 'root'
})
export class SharedService {
activatedRoute: Subject
constructor() { } }
//在子模块中,我们可以使用ActivatedRoute来订阅路由信息,并在激活事件中调用共享服务中的activatedRoute主题 import { Component, OnInit, OnDestroy } from '@angular/core'; import { ActivatedRoute } from '@angular/router'; import { SharedService } from '../shared.service'; import { Subscription } from 'rxjs';
@Component({ selector: 'app-child', templateUrl: './child.component.html', styleUrls: ['./child.component.css'] }) export class ChildComponent implements OnInit, OnDestroy { subscription: Subscription;
constructor(private activatedRoute: ActivatedRoute, private sharedService: SharedService) { }
ngOnInit(): void { this.subscription = this.activatedRoute.params.subscribe(params => { //通过共享服务将激活路线信息发送给父组件 this.sharedService.activatedRoute.next(params['id']); }); }
ngOnDestroy(): void { this.subscription.unsubscribe(); } }
//在父组件中,我们可以在构造函数中订阅共享服务中的activatedRoute主题,以便在路由更改时触发激