Angular2 ngOnDestroy,发出事件
Angular2 ngOnDestroy, emit event
是否可以在 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 => { ... });
希望对你有帮助,
蒂埃里
是否可以在 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 => { ... });
希望对你有帮助, 蒂埃里