How to process HTTP Get request and populate into ng-bootstrap table?

Viewed 782

Following the complete example here:https://ng-bootstrap.github.io/#/components/table/examples, I am implementing a table with sorting, searching, and pagination. I am using Angular 7 and the latest version of ng-bootstrap.

The example uses a static array of objects:

// 1. sort
    let countries = sort(COUNTRIES, sortColumn, sortDirection);

I am trying to figure out a way to pass an array from a subscription of an observable that is returned from an HTTP GET request to this same spot.

The issue is that the HTTP GET takes about a second to retrieve from an API. This causes the subscribe to return an empty array and the sorting, searching, and pagination not to be applied.

How can I have the object service wait for the data to return and the array to be populated before the sorting starts?

I have an API service. Let's call the object type groups. My group service is calling a method in the API service called getgroups(). I have tried: - subscribing to a public behavior subject in the API service.

  • subscribing to the return behavior subject object of getgroups() in the API service.

  • I have tried delaying the sort in the group service in an attempt to wait for the GET request to finish. This appeared to have no affect.

  • I have tried placing the code from the group constructor:

this._search$.pipe(
      tap(() => this._loading$.next(true)),
      debounceTime(200),
      switchMap(() => this._search()),
      delay(200),
      tap(() => this._loading$.next(false))
    ).subscribe(result => {
      this._groups$.next(result.groups);
      this._total$.next(result.total);
    });

    this._search$.next();

in the HTTP GET request AFTER the data is assigned:

this.http.get<Group[]>(environment.apiEndpoint").(
      (resultGroups: Group[]) => {
        groups.next(resultGroups);
HERE -->
      },
      (err: any) => {
        console.log(err);
      },
      () => { 
      }
    );

I have added extended logging which shows the order in which things are called.

  • The API service begins the HTTP GET request
  • The group service logs an empty Behavior Subject object
  • The component controller returns an empty observable
  • The group service returns a list of all groups to the component controller (should only be first 10 per pagination settings
  • The API service finishes the request

I want the API service to begin and finish, and then the group service updates and returns the sorted and paginated data to the component controller.

1 Answers

I found the root cause that was creating these issues. I was populating an Observable with the data from the HTTP request. I used the same observable as the result of the sorting/searching/pagination. These need to be in separate variables in order to work properly.

Related