Home > Enterprise >  RXJS throttletime operator is not working in Angular
RXJS throttletime operator is not working in Angular

Time:02-08

I have a method that is making http calls to the server. this method is being called like 500 times and leading page to crash. I want to separate the calls and make a 200ms delay between calls. I thought of using throttletime operator but it it is not working.

testSubject: Subject<number> = new Subject<number>();


testMethod(id){
   for(let i = 0; i < 500; i  ){
     this.testSubject.next(this.counter);
     this.testSubject.pipe(throttleTime(200)).subscribe(
        (data:any) =>{
           return this.addRow(groupId);        
         }
        )
        this.counter  ;
    }
}

I expect the code above to work as follow:

  • counter gets incremented by 1
  • Subject.next() fires to update the subject with the new value
  • Adding the throttletime when subscribing to the testSubject. so it should make 200ms delay

CodePudding user response:

This is how you might use concatMap to ensure only one request (to addRow) runs at a time.

// The Settup
const testSubject: Subject<number> = new Subject<number>();
testSubject.pipe(

  concatMap(_ => this.addRow(groupId))

).subscribe(JSONdataFromAddRow => {/* Do nothing */});


// Triggering 500 calls
let counter = 0;
for(let i = 0; i < 500; i  ){
  testSubject.next(counter);
  counter  ;
}

CodePudding user response:

You can do something like this, you can use concatMap if you want to wait for the request to finish until you want to send the next one. Use range instead of the for loop to iterate 500 times.

range(1, 500).pipe(
     concatMap(() => {
     return this.yourHttpService.addRow(groupId).pipe(throttleTime(200));
    })
   )
   .subscribe(() => {
     console.log('HTTP successful requests');
   });

This will repeat HTTP requests after successful completion and 200ms delay if the request completes before 200ms.

  •  Tags:  
  • Related