【问题标题】:angular tap into the component life cycle events from a parent module从父模块角度挖掘组件生命周期事件
【发布时间】:2019-08-13 04:03:25
【问题描述】:

我们有以下要求。

我们在应用根组件中有一个主根布局。 在这个布局中,我们有一个 router-outlet,组件通过使用 Angular 路由机制注入到 router-outlet 中。

我们需要从主根布局挂钩到注入到路由器出口的组件的生命周期事件。

因为如果我们注册到路由事件 NavigationEnd,它有时会在组件 ngOnInit 之前被调用。 所以我们知道导航何时结束,但我们不知道组件何时完成工作。理想情况下,我们希望利用组件的生命周期事件。

还要求被注入的组件不继承特殊类或类似的东西......

如何做到这一点?

【问题讨论】:

    标签: angular angular-routing


    【解决方案1】:

    也许您可以创建一个共享服务,当您希望在生命周期挂钩中调用的组件(例如 ngOnInitngOnDestroy 等)时通知该服务。

    @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');
      }
    }
    

    希望这能给你一个提示。

    【讨论】:

    • 你好。我们无法控制被注入的组件。我们不能要求他们调用这个。
    • 哦,知道了。那我不知道怎么做。
    猜你喜欢
    • 2014-10-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-10-17
    • 1970-01-01
    相关资源
    最近更新 更多