gpt4 book ai didi

events - 退订页面更改事件

转载 作者:行者123 更新时间:2023-12-01 15:25:54 25 4
gpt4 key购买 nike

当我不断向导航堆栈添加页面时,会创建越来越多的 SimpleComponent 类实例。出于这个原因,我不止一次订阅“ev”事件并多次触发代码。

您可以通过在我的 plunker 示例中去“那里”和“返回”并在不同情况下触发事件来检查这一点(检查控制台警告的结果)。您还可以看到,即使您回到导航堆栈的顶部,您仍然拥有订阅。

ionViewWillLeave 不起作用可能是因为它不是我要离开的实际 View

我想知道我应该怎么做才能避免这种情况?我希望 SimpleComponent 像旧式 AngularJS 指令一样被包含在内,因为我在我的应用程序中多次使用它。

Here is plunker

export class SimpleComponent {
constructor(private ev: Events) {
this.ev.subscribe('ev', e => {
console.warn(e[0]);
});
}
}


// home.ts template
<simple-component></simple-component>
<button (click)="go()">Go next page</button>
<button (click)="raiseEv()">Raise Event</button>

最佳答案

你可以实现OnDestroy在那里你可以unsubscribe来自 ev :

import { OnDestroy } from '@angular/core';

export class SimpleComponent implements OnDestroy {

ngOnDestroy() {
this.ev.unsubscribe();
}

来自 Angular 2 documentation :

Put cleanup logic in ngOnDestroy, the logic that must run before Angular destroys the directive. This is the time to notify another part of the application that this component is going away. This is the place to free resources that won't be garbage collected automatically. Unsubscribe from observables and DOM events. Stop interval timers. Unregister all callbacks that this directive registered with global or application services. We risk memory leaks if we neglect to do so.

关于events - 退订页面更改事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39616221/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com