检测用户何时离开插座

Detect when user leaves outlet

我有以下路线配置:

{
    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)

有什么方法可以检测用户何时离开bazComponent

当用户从 bazComponent 导航到不包含 baz 出口的任何其他路线时,我需要执行一些代码。

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

您可能应该创建一个 Angular Route Guard and use the CanDeactivate 来执行您希望在离开该路线时执行的代码,如果您需要应用于多条路线,这是更可取的。

在您提到它需要调用该组件内的函数并且它仅适用于您应该使用的单个组件之后 OnDestroy

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

查看 Lifecycle Hooks

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

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