i want to call a method after a window resize, but with 500 ms delay. I did it like this and it is working, but would you do it in the same way? Im new in Angular
resizeEvent$: Subject<MouseEvent> = new Subject<MouseEvent>();
@HostListener('window:resize', ['$event'])
onResize(event) {
this.resizeEvent$.next(event);
}
ngOnInit() {
this.resizeEvent$.debounceTime(300).subscribe( data => this.initJourney());}
You did not mention the version of your Angular and RxJS but I assume you are using RxJS v6+.
So you need to use pipe
method to use debounceTime
First import debounceTime
:
import {debounceTime} from 'rxjs/operators';
Then:
ngOnInit() {
this.resizeEvent$
.pipe(
debounceTime(300)
)
.subscribe( data => this.initJourney());
}
Update
I think you need to change Subject<MouseEvent>
to Subject<Event>
.
Update 2
There is another way which does not involve debounceTime
. You can use setTimeout
in event listener method as follows. Make sure to remove the subject and the subscription in ngOnInit
.
@HostListener('window:resize', ['$event'])
onResize(event) {
setTimeout(() => {
this.initJourney();
},300);
}