How to make an http call every 2 minutes with RXJS?

前端 未结 5 423
猫巷女王i
猫巷女王i 2020-12-03 05:14

I have a service that will make a call to my rest service every 2 minutes. On my service I have the following function

  getNotifications(token: string) {
           


        
5条回答
  •  北荒
    北荒 (楼主)
    2020-12-03 06:11

    If you don't want to make an http call and simply want to do something after 2 minutes, then you can do something like below.

     Observable.interval(2*60*1000)
      .subscribe(() => {
        // do something.
        // or callSomeMethod();
      });
    

    if you are using rxjs 6+ then you can do like this :

      interval(2*60*1000)
      .subscribe(() => {
        // do something.
        // or callSomeMethod();
      });
    

    There is one more important thing you would like to do, You shoud destroy this observable once you leave your current page, because you don't want the extra computation going on behind the scene when these are not actually needed.

    There are multiple options to unsubscribe from this observable.

    1. You should save the reference to the observable and unsubscribe from it in onDestroy method.

       this.observableRef = Observable.interval(60000)
       .subscribe(() => {
         // do something
        });
      
       // call this method in OnDestroy method of the page.
       this.observableRef.unsubscribe();
      
    2. OR use ngx-take-until-destroy

       Observable.interval(60000)
       .takeUntil(this.destroyed$)
       .subscribe(() => {
         //  do something
       });
      

提交回复
热议问题