admin管理员组文章数量:1279176
I find plenty of resources on how to bind Angular HostListeners:
@HostListener('document:click', ['$event'])
handleClick(event: Event) {
// etc
}
but how would I use RxJs instead, to stream it?
documentClickedStream = Observable.fromEvent(/* how to bind this? */)
Not sure how to bind to create a "click anywhere" stream using the decorator pattern suggested in the Angular docs.
I find plenty of resources on how to bind Angular HostListeners:
@HostListener('document:click', ['$event'])
handleClick(event: Event) {
// etc
}
but how would I use RxJs instead, to stream it?
documentClickedStream = Observable.fromEvent(/* how to bind this? */)
Not sure how to bind to create a "click anywhere" stream using the decorator pattern suggested in the Angular docs.
Share Improve this question edited Jul 20, 2018 at 17:32 FlavorScape asked Jul 20, 2018 at 17:18 FlavorScapeFlavorScape 14.3k12 gold badges78 silver badges123 bronze badges 3- 1 what are you actually trying to acplish? you want some other ponent in your application to get notified through ngrx whenever click on this ponent occurs? or? – tlt Commented Jul 20, 2018 at 17:22
- Can you point to decorator documentation link please? – Wand Maker Commented Jul 20, 2018 at 17:25
- oops, updated question, I really meant just how to handle a click anywhere on Host element with RxJs, not ngrx. I typed too fast. – FlavorScape Commented Jul 20, 2018 at 17:25
4 Answers
Reset to default 5I guess the easy way is to just use an intermediary subject:
@HostListener('document:click', ['$event'])
onKeyUp(e:Event) {
this.clickStream$.next(e);
}
then sub to it like normal
this.clickStream$
.asObservable()
.pipe(
// some operators...
)
.subscribe();
Here is my working example. First you need to import this lines into your ponent
import { fromEvent } from 'rxjs/internal/observable/fromEvent';
then put this code into your ponent constructor or into ngOnInit
fromEvent(document, 'click').subscribe(event => {
console.log(event);
})
Use template ref to get ref of button
It will work since we are targeting document.
@ViewChild('btn') btn:ElementRef;
documentClickedStream = Observable.fromEvent(window['document'],'click');
Working example:https://stackblitz./edit/rxjs-window
You can subscribe to RxJs events using below given code as well, add below given code to ngOnInit event:
this.subscribe(fromEvent(document, 'visibilitychange'), (e: Event) => {
console.log('visibilitychange');
this.getVisibilitychange(true);
});
本文标签: javascriptHow do I stream HostListener events using RxJsStack Overflow
版权声明:本文标题:javascript - How do I stream HostListener events using RxJs? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1741220108a2360808.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论