本文介绍了Angular2 ngOnDestroy,发出事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
是否可以在ngOnDestroy上发出自定义事件?我尝试过,但似乎不起作用...我基本上需要知道何时从UI中删除指令.
is it possible to emit a custom event on ngOnDestroy ? I tried, but it seems like it does not work... I basically need to know when a Directive is removed from the UI.
@Output() rowInit = new EventEmitter();
@Output() rowDestroy = new EventEmitter();
ngAfterViewInit() {
this.rowInit.emit(this);
}
ngOnDestroy() {
console.log("I get called, but not emit :(, ngAfterViewInit works :)");
this.rowDestroy.emit(this);
}
推荐答案
我认为您可以使用服务中定义的EventEmitter
而不是组件本身.这样,您的组件将利用服务的此属性来发出事件.
I think that you could use an EventEmitter
defined in a service instead of within the component itself. That way, your component would leverage this attribute of the service to emit the event.
import {EventEmitter} from 'angular2/core';
export class NotificationService {
onDestroyEvent: EventEmitter<string> = new EventEmitter();
constructor() {}
}
export class MyComponent implements OnDestroy {
constructor(service:NotificationService) {
this.service = service;
}
ngOnDestroy() {
this.service.onDestroyEvent.emit('component destroyed');
}
}
其他元素/组件可以在此EventEmitter上订阅以得到通知:
Other elements / components can subscribe on this EventEmitter to be notified:
this.service.onDestroyEvent.subscribe(data => { ... });
希望它对您有帮助,蒂埃里
Hope it helps you,Thierry
这篇关于Angular2 ngOnDestroy,发出事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!