我正在使用Javascript
app Observables
框架中的RxJS
将一些Angular
个事件翻译为Ionic
。我想在“客户端”调用.subscribe()时开始侦听事件,并在调用.unsubscribe()时停止侦听它们。我查看了Observable
课程的文档,但我无法看到如何做到这一点。
所以,假设有“onSubscribe”和“onUnsubscribe”方法,我想做这样的事情:
import { Observable, Subject } from 'rxjs';
...
on(name: string) : Observable<Event> {
let observable = new Subject<any>();
observable.onSubscribe(() => {
this.addEventListener(name, (event) => {
observable.next(event);
});
});
observable.onUnsubscribe(() => {
this.removeEventListener(name);
});
return observable;
}
有没有办法实现这个目标?
谢谢!
答案 0 :(得分:0)
import { Observable, Subject } from 'rxjs';
...
const unsubscribe;
on(name: string) : Observable<Event> {
let observable = new Subject<any>();
// subscribe method returns unsubscribe function, so you have to save in some varibale then call it.
this.unsubscribe = observable.subscribe(() => {
this.addEventListener(name, (event) => {
observable.next(event);
});
});
return observable;
}
// some where else you can do this
unsubscribe();