我们有以下要求。
我们在应用程序根组件中具有主根布局。在此布局中,我们有一个路由器输出,并通过使用角路由机构将组件注入路由器输出。
我们需要从主根布局挂钩到被注入路由器输出的组件的生命周期事件中。
因为如果我们注册到路由器事件导航,有时会在组件ngoninit之前调用。因此,我们知道导航何时结束,但我们不知道该组件何时完成工作。理想情况下,我们想利用组件的生命周期事件。
需求也是要注入的组件不会继承特殊类或类似的东西...
如何完成?
也许您可以创建一个共享服务,当您要在生命周期挂钩(例如ngOnInit
,ngOnDestroy
等)中调用组件时,您可以告知该服务。
@Injectable({
providedIn: 'root'
})
export class LifeCycleHookService{
private hookSubject = new Subject<any>();
onHookFired = this.hookSubject.asObservable();
// component: Component - Reference to the component
// hookType: Enum | string - OnInit, OnDestroy etc.
fireHook = (component, hookType) => {
this.hookSubject.next({component, hookType});
}
}
然后在您的父组件中,您可以订阅服务的onHookFired
。
@Component(
...
)
export class ParentComponent implements OnInit{
constructor(private hookService: LifeCycleHookService){}
ngOnInit(){
this.hookService.onHookFired.subscribe((event) => {
// event.component
// event.hookType
})
}
}
然后在您的孩子组件中,您可以在生命周期挂钩上通知服务。
@Component(
...
)
export class ChildComponent implements OnInit, OnDestroy{
constructor(private hookService: LifeCycleHookService){}
ngOnInit(){
this.hookService.fireHook(this, 'onInit');
}
ngOnDestroy(){
this.hookService.fireHook(this, 'onDestroy');
}
}
希望这给您一个提示。