What is the best way to populate an Angular Bootstrap Table Widget with data obtained from an API request?

I am currently in the process of making an API call and utilizing the received data in a Bootstrap Angular Table Widget.

The specific widget I am utilizing can be found here: Complete example (Angular powered bootstrap widget)

Ensure you are working with the complete example that includes the service and pagination features.

I attempted to replace the existing data with the response from my API call.

constructor(public service: CountryService) {
    this.countries$ = service.countries$;
    this.total$ = service.total$;
    this.headers = new QueryList<NgbdSortableHeader>();
}

API service:

getusers2() {
    return this.http.get<Country[]>(this.getusersEndpoint, this.httpOptions);
}

While this approach partially works and displays the expected output in the table, the service still relies on the hard-coded class COUNTRIES. As a result, the filtering, pagination, and searching functionalities do not function properly. How can I resolve this issue?

The primary objective is to set up a basic table on the page, fetch the data, and update the table accordingly with the API response.

An ideal solution would involve:

<ngbd-table-skeleton ngIf=loading></ngbd-table-skeleton>
<ngbd-table-complete ngIf=!loading [data]="countries"></ngbd-table-complete>

Here, I would set loading to true in the OnInit function, fetch the data, set the data, toggle loading to false, and display the updated table with functional pagination, filtering, and sorting.

Implementing this approach might be challenging given my current level of expertise in Angular. If anyone has a potential solution or alternative method, I would greatly appreciate your insights.

Answer №1

To effectively utilize the "country.service", it is crucial to modify the code to fetch data from the API instead of hardcoding values like "COUNTRIES". Additionally, integrating "pipe(map)" is essential for handling observables efficiently.

It is recommended to send parameters such as sortColumn, sortDirection, pageSize, page, and searchTerm to the API to retrieve only relevant data. Thus, the _search function should be updated as follows:

The revised _search function will look like this:

private _search(): Observable<SearchResult> {
    const { sortColumn, sortDirection, pageSize, page, searchTerm } = this._state;
      return this.httpClient.get(....) //<--call to your API

In cases where there are few items, you can cache the data and return either the cached values or make a call to the API for the entire list of countries.

countries:Country[]; //<--a variable to store the whole countries

private _search(): Observable<SearchResult> {
    const { sortColumn, sortDirection, pageSize, page, searchTerm } =
      this._state;
   
    //if "this.countries" have values, obs%= of(this.countries)
    //else obs$=the call to your API

    const obs$=this.countries?of(this.countries):
               this.httpClient.get(..).pipe(tap((res: Country[])=>{
                    this.countries=res;
               }))

    //we work with observables using "pipe"
    return obs$.pipe(
      map((res: Country[]) => {
        //you sort:
        let countries = sort(res, sortColumn, sortDirection);

        //filter
        countries = countries.filter((country) =>
          matches(country, searchTerm, this.pipe)
        );
        const total = countries.length;

        //paginate
        countries = countries.slice(
          (page - 1) * pageSize,
          (page - 1) * pageSize + pageSize
        );

        return { countries, total };
      })
    );
  }

It is evident that managing observables is comparable to handling arrays, as both involve using them within a pipe.map operation.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Generate a fresh JSON object following a click event triggered by an HTTP PUT request

I have the following structure in JSON format: "disputes": [ { id: "", negotiation_type: "", history:{ user_flag: "", created_at: "", updated_at: "", created_by: null, updated_by: null, ...

Tips for executing horizontal drag and replace

Scenario: I am attempting to implement a drag and drop feature for three columns to reorder them horizontally. I referred to the drag and drop example on this demo page, but I need the ability to only drag items horizontally. My current markup structure is ...

Angular 2.0 encountered an unexpected value from the module 'AppModule' which appears to be an '[object Object]'

Every time I attempt to load my angular version 2.0 application, I encounter the following error: (index):21 Error: Error: Unexpected value '[object Object]' imported by the module 'AppModule' import { ModuleWithProviders } from ' ...

Can a single shield protect every part of an Angular application?

I have configured my application in a way where most components are protected, but the main page "/" is still accessible to users. I am looking for a solution that would automatically redirect unauthenticated users to "/login" without having to make every ...

Replacing a component dynamically within another component in Angular 2

I am currently working on integrating a component within another component that has its own view. The component being loaded will be determined dynamically based on specific conditions. Essentially, I am looking to replace one component with another compo ...

Retrieve the value of an HTML attribute from a nested element with Angular 2

I've created an Angular 2 accordion header component that stores its collapsed state in the class attribute of the root element. Within this component, there is a chevron glyphicon that I would like to toggle between two different icons based on the ...

TS2349 emerges when incorporating lazy-loading in React

I've been working on refactoring a React 18 app to incorporate lazy loading, following the guidelines provided in the official documentation: One effective method to implement code-splitting in your application is through the dynamic import() syntax ...

Can a TypeScript-typed wrapper for localStorage be created to handle mapped return values effectively?

Is it feasible to create a TypeScript wrapper for localStorage with a schema that outlines all the possible values stored in localStorage? Specifically, I am struggling to define the return type so that it corresponds to the appropriate type specified in t ...

Issue: Button ClickEvent is not triggered when the textArea is in onFocus mode

Is there a way to automatically activate a button ClickEvent when the textArea input is focused? Keep in mind that my textArea has some styles applied, causing it to expand when clicked. Here is an example: https://stackblitz.com/edit/angular-ivy-zy9sqj?f ...

Error encountered due to a circular reference in the dependency library

Whenever I attempt to run my application, I encounter the following error: > npm start Starting the development server... ts-loader: Using <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="42363b32273121302b323602716c776c71"& ...

I am puzzled as to why my function's return type transforms into a promise when I interact with the cell.value or use console.log

Recently, I embarked on the journey of coding a validation process for my Excel Sheet. To keep the code concise, I implemented it in a straightforward manner. Here is a snippet of my source code: function main(workbook: ExcelScript.Workbook) { console. ...

Prisma atomic operations encounter errors when attempting to update undefined values

According to the Prisma Typescript definition for atomic operations, we have: export type IntFieldUpdateOperationsInput = { set?: number increment?: number decrement?: number multiply?: number divide?: number } Let's take a look at the Pris ...

Ways to invoke a function in HTML aside from using the (click)="function()" syntax

How can I display data from a GET request to the WordPress API as the page loads in an Ionic app using Angular? I am able to retrieve my desired post list, but only when I use a button click event to call the method in the HTML. Since this is my first att ...

Angular - Ensuring service completion before proceeding with navigation

I'm currently facing an issue where I need to populate data in a service before navigating, but the navigation is happening before the data is ready. Here's the code in my service: addToken(token) { this.cookieService.set( 'token', ...

Angular6 Error: Property 'catch' is missing

I am new to Angular and have a basic understanding of it. I am interested in learning how to use HttpClient to create a JSON file instead of relying on a real server. I have set up a service and imported HttpClient: service.ts import { Injectable } from ...

Exploring the functionality of the Angular snackbar feature

I have created a simple snackbar with the following code: app.component.ts: ngOnInit(){ this.dataService.valueChanges.pipe( filter((data) => data === true), switchMap(() => { const snackBarRef = this.matSnackBar.open ...

Ways to change the Date format to something like [25 Jan 2024]

https://i.sstatic.net/BvSc8.png I am looking to convert the date format to appear as "25 Jan 2024" in my Angular application. Currently, the date is displayed as "25-01-2024" but I want it to be in the format "25 Jan 2024". Can anyone help me resolve this ...

Error: The browser threw a TypeError because Object(...) is not a function

I am having an issue with using Ionic Image Loader for image loading and caching. While there are no errors during compilation, I encounter the following error in the browser. Below are the details from my package.json file. As a newcomer to Ionic and Angu ...

Encountering an error on Ionic 4, Angular 8: Unable to access property 'subscribe' of undefined

I have a project that utilizes Ionic 4 and Angular 8. The project requires integration with a payment gateway service, which I am accomplishing using the Ionic 4 InAppBrowser plugin to open the payment gateway site. This is how I've implemented it: ...

Steps to Transform String Array into Prisma Query Select Statement

I have a requirement to dynamically select Prisma columns based on client input: ['id', 'createdAt', 'updatedAt', 'Order.id', 'Order.Item.id', 'Order.Item.desc'] The desired format for selection ...