是否可以在ngOnDestroy上发出自定义事件?我试过,但似乎它不起作用……我基本上需要知道何时从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而不是组件本身.这样,您的组件将利用服务的此属性来发出事件.
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上订阅以通知:
this.service.onDestroyEvent.subscribe(data => { ... });
希望它能帮到你,蒂埃里