bluray
bluray

Reputation: 1963

Angular - send multiple request without waiting all

I would like to send many requests and display results without waiting for all requests. For testing, I insert to my PHP API method this code: sleep(rand (1,10)). So, response arrives for a different length of time. But my angular client wait for all responses and then display result:

let requests = [];
    for(let id of ids)
      requests.push(this.http.get(`api/some/${id}`));
    this.results$ = forkJoin(requests);

And template:

<p *ngFor="let result of results$ | async">{{result.id}}</p>

How to display result when arrives without waiting for all responses? And can I sort result, for example by ID?

Thanks

Upvotes: 0

Views: 457

Answers (2)

Raby&#226; Raghib
Raby&#226; Raghib

Reputation: 154

as yo chauhan said. use merge instead of forkjoin.

let requests = [];
for(let id of ids)
    requests.push(this.http.get(`api/some/${id}`));
this.results$ = merge(requests);

& for sorting stuf u can create a custom pipe that sorte the array.

import { Pipe, PipeTransform } from '@angular/core';

@Pipe({
    name: 'sort'
})
export class SortPipe implements PipeTransform {

    transform(array: any[],sortBy: string): any[] {
        return array.sort(function(a, b) {
            if (a[sortBy] < b[sortBy])
                return -1;
            if (a[sortBy] > b[sortBy])
                return 1;
            return 0;
        });
    }

}

and use it in your Html template.

<p *ngFor="let result of (results$ | async) | sort: 'id'">{{result.id}}</p>

Upvotes: 1

AliF50
AliF50

Reputation: 18849

I think forkJoin waits until it is all resolved before emitting.

What I would do is have a results array locally and push to this one.

let results = [];
for (let id of ids)
   this.http.get(`api/some/${id}`).subscribe(result => {
     this.results = [...this.results, ...result];
   });
<p *ngFor="let result of results">{{result.id}}</p>

Upvotes: 0

Related Questions