Call a method after subscription Angular

81 views Asked by At

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());}
2

There are 2 answers

2
Harun Yilmaz On BEST ANSWER

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);
}
1
Pseudalitos On

ok, thx for your fast reply (im using angular 7). But isnt there another way:

.subscribe( data => this.initJourney());

looks weird, data is unused