代码之家  ›  专栏  ›  技术社区  ›  Ivan Aguilar

检测用户何时离开插座

  •  1
  • Ivan Aguilar  · 技术社区  · 8 年前

    我有以下路由配置:

    {
        path: 'foo',
        component: 'fooComponent'
    },
    {
        path: 'bar',
        children: [
            {
                path: ':barId',
                component: barComponent,
                children: [
                    {
                        path: ':bazId',                
                        component: bazComponent,
                        outlet: 'baz'
                    }
                ]
            }
        ]
    }
    

    我现在在 bazComponent . 当前URL为 http://localhost:4200/bar/barId/(baz:bazId)

    有没有办法检测用户何时离开 Baz组件 ?

    当用户从中导航时,我需要执行一些代码 Baz组件 到不包含 baz 出口

    编辑: 我必须执行的代码位于无法移动的组件内的函数内。

    2 回复  |  直到 8 年前
        1
  •  2
  •   J J B    8 年前

    您可能应该创建一个角度 Route Guard 并使用 CanDeactivate 要执行您希望在离开该路由时执行的代码,如果您需要应用于多个路由,则最好这样做。

    在您提到它需要调用该组件中的函数之后,它只适用于您应该使用的单个组件 OnDestroy .

    class AppComponent implements OnDestroy {
      ngOnDestroy() {
        // Call to function/method here.
      }
    }
    

    查看 Lifecycle Hooks .

        2
  •  0
  •   Liv    8 年前

    onDestroy是否足以满足您的用例?

    @请参见 https://angular.io/api/core/OnDestroy

    推荐文章