Angular 2 RxJS checks if the mouse event continues after a delay

I am using Angular 2 to create a directive. I have the following host component related events:

host: { '(mouseenter)': 'onMouseEnter($event)', '(mouseleave)': 'onMouseLeave($event)' } 

I also created two threads and listeners in the directive for managing two events

 export class PopupDirective { private _mouseEnterStream: EventEmitter<any> = new EventEmitter(); private _mouseLeaveStream: EventEmitter<any> = new EventEmitter(); onMouseEnter($event) { this._mouseEnterStream.emit($event); } onMouseLeave($event) { this._mouseLeaveStream.emit($event); } } 

I want my subscribe to be mouseenter only if the mouseenter event is still active after a fixed delay (i.e. a mouseleave did not happen). I tried to do it this way, but it won’t work (which makes sense, I just don’t know how to fix it).

 this._mouseEnterStream.flatMap((e) => { return Observable .of(e) .takeUntil(this._mouseLeaveStream); }).delay(2000).subscribe( () => console.log('yay, it worked!') ); 

Does anyone with Angular 2 / RxJS experience know how I should approach this?

+5
source share
2 answers

Gunter's answer is exactly what you expect, but you should use the of operator instead of return one that does not exist.

 this._mouseEnterStream.flatMap((e) => { console.log('_mouseEnterStream.flatMap'); return Observable .of(e) .delay(2000) .takeUntil(this._mouseLeaveStream); }).subscribe( (e) => { console.log('yay, it worked!'); console.log(e); } ); 

See the corresponding plan: https://plnkr.co/edit/vP3xRDXxFanqzLEKd3eo?p=preview .

In addition, Angular has a proposal aimed at simplifying the creation of observable objects from DOM events using Rx via template syntax.

+4
source

Looks a lot like How to wait out time in RxJS?

 this.myStream = this._mouseEnterStream .flatMap((e) => { return Observable .of(e) .delay(2000) .takeUntil(mouseLeaveStream); }); myStream.subscribe((x) => { console.log('onNext: ', x); }); 

I do not use TS or Rx on my own (only Dart), so I do not know if this is the correct syntax or if the names of the operators match those available for Angular.

+3
source

Source: https://habr.com/ru/post/1242678/


All Articles