我想在取消订阅可观察对象时删除事件侦听器。我的问题是如何检查是否删除了事件监听器。有什么方法可以检查事件监听器是否已删除?
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=bank
DB_USERNAME=root
DB_PASSWORD=
还有我的组件:
export class BroadcastService {
public events: Observable < any > ;
public channel = new BroadcastChannel('test_channel');
constructor() {
this.events = Observable.create((observer) => {
const listener = (ev) => {
observer.next(ev.data),
console.log("on")
};
this.channel.addEventListener('message', listener);
return () => {
this.channel.removeEventListener('message', listener);
};
});
}
public addPerson(person: any) {
this.channel.postMessage(person);
}
}
答案 0 :(得分:1)
您可以在服务中手动执行此操作:
import { Observable } from 'rxjs';
export class BroadcastService {
public events: Observable<any>;
public channel = new BroadcastChannel('test_channel');
constructor() {
this.events = Observable.create((observer) => {
this.channel.addEventListener('message', (ev) => {
observer.next(ev.data)
});
return () => {
this.channel.removeEventListener('message', (ev) => {
observer.next({
...ev.data,
removed: true
})
});
};
});
}
public addPerson(person: any) {
this.channel.postMessage(person);
}
}
订阅后,您可以检查数据是否具有removed
属性。