-1

I need to implement a service that will go fetch Stock details every 2 minutes. Stock details are more prone to change therefore, I have decided to fetch it every 2 minutes. I have implemented fetching the Stock details for just one instance, but how do I change my code so that it fires a request every 2 minutes during the first 12 hours of the day.

In brief :

  1. I need to fetch Stock details every 2 minutes.

  2. I only need to fire a request from 10AM to 3PM.

    this.myService.getDetailsStock(1).subscribe(
     (response) =>
     {
       this.allStockDetails= response.details;
    
     },
     (error) => 
     {
       alert(JSON.stringify(error));
     }
    );
    
Sharon Watinsan
  • 9,620
  • 31
  • 96
  • 140
  • 1
    [`setInterval`](https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/setInterval) – Liam Aug 13 '21 at 16:11
  • 1
    setInterval is not idiomatic in Angular. Using RxJS interval as described by the answer by Ritesh Waghela is better. – Clashsoft Aug 13 '21 at 16:27

1 Answers1

3

You can use RxJS interval operator for this purpose: Link https://rxjs.dev/api/index/function/interval

  import { interval } from 'rxjs';
    
  const apiIntervalSubscription = interval(2 * 60 * 1000)
     .pipe(mergeMap(() => this.myService.getDetailsStock(1)))
     .subscribe(data => console.log(data))

To stop firing the API after a specific time, we can create another interval where we can check the time every minute and when we reach a particular time, we can unsubscribe the apiIntervalSubscription after that time, like this:

apiIntervalSubscription.unsubscribe(); 
Ritesh Waghela
  • 3,474
  • 2
  • 19
  • 25
  • Given that the OP wants every x seconds switchMap is likely a better choice – Liam Aug 13 '21 at 16:15
  • `Observable.interval` has been deprecated for some time. it should be `import { interval } from 'rxjs';` now – Liam Aug 13 '21 at 16:16
  • @Liam Angular/RxJS version is not specified in OP. Still I have updated the answer considering the latest version. – Ritesh Waghela Aug 13 '21 at 16:20
  • switchMap is good when cancelling is required, here OP wants the API call in every 2 seconds, hence interval with mergeMap will serve the purpose. – Ritesh Waghela Aug 13 '21 at 16:22
  • this code make a call after 2 minutes, how can we make an inital call and then every 2 minutes ? – inttyl Aug 24 '22 at 15:14
  • What if the initial call returns an error response, would you still like to make call after every 2 minute? – Ritesh Waghela Aug 25 '22 at 14:17