取消订阅页面更改事件
Unsubscribing from events on page change
当我不断向导航堆栈添加页面时,会创建越来越多的 SimpleComponent class 实例。出于这个原因,我不止一次订阅 "ev" 事件并不止一次触发代码。
您可以通过在我的 plunker 示例中转到 "there" 和 "back" 并在不同情况下触发事件来检查(检查控制台警告以获取结果)。您还可以看到,即使您移回导航堆栈的顶部,您仍然拥有订阅。
ionViewWillLeave 无法正常工作,可能是因为它不是我要离开的实际视图
我想知道我应该怎么做才能避免这种情况?我希望像旧式 AngularJS 指令一样包含 SimpleComponent,因为我在我的应用程序中多次使用它。
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();
}
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.
我决定将负责处理事件后接收操作的代码移至@Injectable,这解决了问题
当我不断向导航堆栈添加页面时,会创建越来越多的 SimpleComponent class 实例。出于这个原因,我不止一次订阅 "ev" 事件并不止一次触发代码。
您可以通过在我的 plunker 示例中转到 "there" 和 "back" 并在不同情况下触发事件来检查(检查控制台警告以获取结果)。您还可以看到,即使您移回导航堆栈的顶部,您仍然拥有订阅。
ionViewWillLeave 无法正常工作,可能是因为它不是我要离开的实际视图
我想知道我应该怎么做才能避免这种情况?我希望像旧式 AngularJS 指令一样包含 SimpleComponent,因为我在我的应用程序中多次使用它。
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();
}
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.
我决定将负责处理事件后接收操作的代码移至@Injectable,这解决了问题