Home > OS >  Receiving updates from API every second
Receiving updates from API every second

Time:06-03

Below is an Angular RxJS code that makes an API call to get information from an API service However, I need the request to be made every second. I understand that I need to use Observables but not sure how to proceed.

getInformation$(id: number): Observable<publicInformation> {
    return forkJoin([
        this._http.get<name>(`api/name/${id}`),
        this._http.get<CurrentInformations>(`api/currentInformation/${id}`)
      ]).pipe(
        map(([name, currentInformation]) => {return { ...name, ...currentInformation}
      })
    );
}

CodePudding user response:

You can use rxjs interval operator for polling.

CodePudding user response:

This approach should work well (in pseudo code)

interval
   pipe(
     exhaustMap 
        forkJoin
   )

Note: the exhaustMap will ignore the interval event if the forkJoin takes longer than 1s, and then it will continue every 1s

CodePudding user response:

You can use interval to ping the server every x milliseconds. You can the do the forkJoin in the pipe within a concatMap.

@Injectable({ providedIn: 'root' })
export class ExampleService {
  private readonly INTERVAL = 1000;

  constructor(private readonly _http: HttpClient) {}

  getInformation$(id: number): Observable<publicInformation> {
    return timer(0, this.INTERVAL).pipe(
      concatMap(() =>
        forkJoin({
          name: this._http.get<name>(`api/name/${id}`),
          currentInformation: this._http.get<CurrentInformations>(
            `api/currentInformation/${id}`
          ),
        })
      )
    );
  }
}

Subscribe to the component's Observable like this:
Note: You could have used an array too, this example just uses two different properties.

<div *ngIf="information1$ | async as data">
  <p>Name: {{ data.name.first }} {{ data.name.last }}</p>
  <p>
    {{ data.name.first }}'s Current Time: {{ data.currentInformation.current }}
  </p>
</div>

<hr />

<div *ngIf="information2$ | async as data">
  <p>Name: {{ data.name.first }} {{ data.name.last }}</p>
  <p>
    {{ data.name.first }}'s Current Time: {{ data.currentInformation.current }}
  </p>
</div>

The component:

export class AppComponent {

  information1$ = this.exampleService.getInformation$(123);
  information2$ = this.exampleService.getInformation$(456);

  constructor(private exampleService: ExampleService) {}
}

Here is a working example

Note: See the intercept service to see how the dummy network api works. This isn't needed if an actual API exists.

  • Related