How to make an HTTP call every 2 minutes using RXJS?

I have a service that will call my leisure service every 2 minutes. In my service, I have the following function

  getNotifications(token: string) {
     const body = 'xxxxxxxxx=' + token;
     return this.http.post('/rest/ssss/ddddddd/notificationcount', body, this.options)
          .map((res) => res.json());
  }

In my component, I call my utility function to call the API.

this.notificationService.getNotifications(this.token).subscribe((data) => {
  console.log(data);
});

I want to make this call every 2 minutes, what is the best way to do this?

+11
source share
4 answers

Since you are already using Observables, just use it fully :) Obersvable.interval()your good friend is here:

In your component do this:

Observable
    .interval(2*60*1000)
    .timeInterval()
    .flatMap(() => this.notificationService.getNotifications(this.token))
    .subscribe(data => {
        console.log(data);
    });

Explanation:

  1. .interval() creates an observable that generates an event every 2 minutes.
  2. .timeInterval() , , .
  3. .flatMap() , . , 0-, 2-, 4-, 6-.... . ( , .then() )), .. 2- 0- , 4- 2- ..
  4. .subscribe()

:

(rxjs5 ), :

interval(2 * 60 * 1000)
    .pipe(
        flatMap(() => this.notificationService.getNotifications(this.token))
    )
    .subscribe(data => console.log(data))
+30

http- - 2 , - .

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

, : , , , , .

.

  1. onDestroy.

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

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

If you are using rxJs 6+, you can simply use the interval method. like this -

import { interval } from 'rxjs';

interval(3000).subscribe(x => /* do something */)
0
source
import {Observable} from 'rxjs/Rx';

  Observable.interval(2 * 60 * 1000).subscribe(x => {
    callyourmethod();
  });

Update after comment

this.interval = setInterval(() => {
        this.yourservicecallmethod();
    }, 2 * 60 * 1000);
-1
source

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


All Articles