【问题标题】:How to call a method after old component removed from DOM when navigating in Angular?在Angular中导航时如何从DOM中删除旧组件后调用方法?
【发布时间】:2020-11-05 11:05:43
【问题描述】:

在单击从 ComponentA 导航到 ComponentB 的 routerLink 后,我正在尝试运行一个方法(在 ComponentB 上)。一旦导航完全完成(即 ComponentA 已被销毁 + 从 DOM 中删除),此方法就会被触发,这一点很重要。

我已经尝试在 ComponentB 的 ngOnInit()ngAfterViewInit() 中触发这个,以及订阅路由器 NavigationEnd:

this.router.events.subscribe(event => {
            if (event instanceof NavigationEnd) {
                this.doSomething();
            }
        });

然而,所有这些触发之前 ComponentA 从DOM 中删除。如果我在doSomething() 中放置一个断点,则 ComponentA 在触发时仍然在 DOM 中可见。据我所知,当前调用发生在 ComponentA 上调用 ngOnDestroy() 和实际从 DOM 中销毁/删除之间。

似乎发生了什么:

routerLink clicked
ComponentB created
NavigationEnd event fired
ComponentA ngOnDestroy()
ComponentB ngOnInit()
ComponentB ngAfterViewInit()
ComponentA destroyed (removed from DOM)

我需要什么:

routerLink clicked
ComponentB created
ComponentA destroyed (removed from DOM)
ComponentB doSomething()

我怎样才能做到这一点?

【问题讨论】:

    标签: angular typescript angular-router


    【解决方案1】:

    RouterOutlet 指令公开了一个deactivateEvents @Output property

    @Output('deactivate') deactivateEvents = new EventEmitter<any>();
    

    当当前路由被停用时会发出这个(这也涉及到此时组件被销毁):

    deactivate(): void {
      if (this.activated) {
        const c = this.component;
        this.activated.destroy();
        this.activated = null;
        this._activatedRoute = null;
        this.deactivateEvents.emit(c);
      }
    }
    

    你可以这样使用它:

    <router-link (deactivate)="onDeactivate($event)"></router-link>
    

    现在,根据您当前的情况,您可以使用服务通知ComponentB

    【讨论】:

      猜你喜欢
      • 2023-03-13
      • 2019-12-19
      • 2018-10-09
      • 2019-02-14
      • 1970-01-01
      • 2023-01-30
      • 2020-04-28
      • 2018-02-03
      • 1970-01-01
      相关资源
      最近更新 更多