要强制所有子组件运行它们的constructor和ngOnInit函数,可以使用Angular的路由守卫来实现。下面是一个示例的解决方案:
RouteObserverService
的服务来观察路由的变化并通知子组件:import { Injectable } from '@angular/core';
import { Router, NavigationEnd } from '@angular/router';
import { Observable, Subject } from 'rxjs';
@Injectable({
providedIn: 'root'
})
export class RouteObserverService {
private routeChangeSubject = new Subject();
constructor(private router: Router) {
this.router.events.subscribe(event => {
if (event instanceof NavigationEnd) {
this.routeChangeSubject.next(event.urlAfterRedirects);
}
});
}
getRouteChangeObservable(): Observable {
return this.routeChangeSubject.asObservable();
}
}
RouteObserverService
的getRouteChangeObservable()
方法,并在路由变化时执行相关函数:import { Component, OnInit, OnDestroy } from '@angular/core';
import { Subscription } from 'rxjs';
import { RouteObserverService } from '路径/到/RouteObserverService';
@Component({
selector: 'app-child-component',
templateUrl: './child-component.component.html',
styleUrls: ['./child-component.component.css']
})
export class ChildComponentComponent implements OnInit, OnDestroy {
private routeChangeSubscription: Subscription;
constructor(private routeObserverService: RouteObserverService) { }
ngOnInit() {
// 在ngOnInit中执行的代码
console.log('ChildComponent ngOnInit');
this.routeChangeSubscription = this.routeObserverService.getRouteChangeObservable().subscribe(() => {
// 在路由变化时执行的代码
console.log('ChildComponent route changed');
});
}
ngOnDestroy() {
this.routeChangeSubscription.unsubscribe();
}
}
通过以上步骤,当父组件的路由发生变化时,子组件的constructor和ngOnInit函数都会被执行。
上一篇:Angular8路由为空或参数化
下一篇:Angular8模板驱动表单抛出错误:TypeError: 无法读取未定义的属性'ProviderName',在Object.eval [作为updateDirectives]处。