Tips for initializing matTableDataSource with values from an Observable during the initial loading phase

Having difficulty populating the MatTableDataSource when the application starts up. Upon startup, the table is empty with a *matNoDataRow message displayed. However, once I click on any column to sort or input anything in the filter, the data immediately appears.

I attempted using hardcoded values for table rows and it worked fine - everything loaded upon startup. I have a functional StackBlitz example where I replicated everything except for the subscription because it retrieves values from my database: StackBlitzExampleOfHardcodedArray

I also tried populating an array in the service and calling it in the component after it's done loading but unfortunately, the rows still did not show.

This is my original method:


parseUserData: any;
returnValue: any = [];
getAllBooksFromDatabase(): BooksData[] { //all books from Bookshelf
  this.returnValue.splice(0, this.returnValue.length);
  this.data.getBooks().subscribe((data: any) => {
    this.parseUserData = JSON.parse(JSON.stringify(data));
    this.parseUserData.map((item: any) => {
      if (item.fine != 0) {
        this.returnValue.push({
          uid: item.uid,
          bid: item.bid,
          bookTitle: item.bookTitle,
          authorLastName: item.authorLastName,
          authorFirstName: item.authorFirstName,
          issuedDate: item.issuedDate,
          period: item.period,
          fine: item.fine,
          warning: item.warning
        });
      }
    })
    return this.returnValue;
  }
}

EDIT: This is my service method for fetching data:


public getBooks(): Observable<any> {
  return this.http.get('http://localhost:8080/books')
    .pipe(map((books: any) => books));
}

EDIT: Here is part of the result - books:


[
  {
    "warning": "",
    "issuedDate": "in library",
    "period": "0",
    "bookTitle": "Balade Petrice Kerempuha",
    "bid": "158744286",
    "fine": "0",
    "authorLastName": "Krleža",
    "authorFirstName": "Miroslav",
    "bookGenre": "poetry",
    "uid": ""
  },
  ...
 ]

How can I display all table rows upon startup?

Your advice is greatly appreciated. Thank you!

Answer №1

The this.returnValue variable is assigned asynchronously, leading to it being empty upon return. To resolve this issue, consider using the RxJS map operator in conjunction with Array's map and filter functions. Rather than returning the value directly, assign it within the ngOnInit hook.

Implement the following solution:

ngOnInit() {
  this.getAllBooksFromDatabase().subscribe(
    books => {
      this.dataSourceBook = new MatTableDataSource(books);
      this.dataSourceBook.paginator = this.paginator;
      this.dataSourceBook.sort = this.sort;
    }
  );
}

getAllBooksFromDatabase(): Observable<BooksData[]> { // Fetch all books from Bookshelf
  return this.data.getBooks().pipe(
    map(data => {
      return data
        .filter(item => item.fine != 0)        // <-- Add your condition here
        .map(item => {
          return {
            uid: item.uid,
            bid: item.bid,
            bookTitle: item.bookTitle,
            authorLastName: item.authorLastName,
            authorFirstName: item.authorFirstName,
            issuedDate: item.issuedDate,
            period: item.period,
            fine: item.fine,
            warning: item.warning
          }
        })
      })
  );
}

For more information on handling asynchronous data, refer to this resource.

Answer №2

Give this a shot

  displayBooks() {
    this.libraryData
      .fetchLibraryBooks()
      .pipe(
        filter((data) => !!data),
        map((data: any[]) => {
          data.map((item: any) => {
            if (item.fine != 0) {
              return {
                uid: item.uid,
                bid: item.bid,
                bookTitle: item.bookTitle,
                authorLastName: item.authorLastName,
                authorFirstName: item.authorFirstName,
                issuedDate: item.issuedDate,
                period: item.period,
                fine: item.fine,
                warning: item.warning,
              };
            }
          });
        })
      )
      .subscribe((books: LibraryBookData) => {
        this.dataSource = new MatTableDataSource(books);
        this.dataSource.paginator = this.paginator;
        this.dataSource.sort = this.sort;
      });
  }

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

I am unable to retrieve the values from a manually created JavaScript list using querySelectorAll()

const myList = document.createElement("div"); myList.setAttribute('id', 'name'); const list1 = document.createElement("ul"); const item1 = document.createElement("li"); let value1 = document.createTe ...

Optimal method for retrieving data from a JSON object using the object's ID with a map

Can you teach me how to locate a json object in JavaScript? Here is a sample Json: { "Employees" : [ { "userId":"rirani", "jobTitleName":"Developer", "preferredFullName":"Romin Irani", "employeeCode":"E1", "region":"CA", "phoneNumber":"408-1234567", " ...

Issue encountered when retrieving ProductCardComponent: Unable to access property 'Payload' as it is undefined

I encountered an issue while trying to extract the code of a card component into a separate Angular component. The code was functioning properly, but when I moved it to another component and referenced it in the products component, it gave me an error mess ...

Encountering an npm issue: Clash in peer dependency between @angular/fire version 6.0.2 while trying to add angular/fire module

While trying to install the angular/fire module for Firebase authentication, I encountered a conflicting peer dependency error in the terminal. The error is related to upgrading an angular/compiler module from version 12.2.17 to version 12.0.0, which seems ...

What is the reason for the inclusion of information in the error log by the `ng

After initiating a production build with the command ng build --configuration production, Angular logs some information to the error log: - Generating browser application bundles (phase: setup)... ✔ Browser application bundle generation complete. ✔ Bro ...

Automatic Guarding in the Angular Router

My attempts to implement the router Autoguard have hit a roadblock - the canActivate function is not executed when redirecting users to another component. Below is an example of my code: LoginComponent.ts public doLogin(): void { const userName: ...

Interference of NestJS provider classes in separate event loops causing conflicts

I'm currently facing an issue where my shared library injectables are conflicting with each other. The bootstrap file initiates this file alongside a proxy server to start local microservices import { serviceA } from '@company/serviceA' imp ...

ng-class not recognizing multiple arguments

I am facing an issue where I am trying to check two parameters in order to set a class using ng-class, but it seems to only work with one parameter. Below is the code I am using: ng-class="{'alert-viewed': item.viewed && item.status <= 0}" ...

What is the best way to set the text color of cell data in a mat-table to white for the entire row when the row is selected as

Is there a way to change the text color when a row is selected in my application? I have already figured out how to change the background color of the row, but how can I target the text within the cells? I'm considering using a similar approach to th ...

Troubleshooting image quality problem with @capacitor/camera on web platform

Our image capture process involves utilizing the @capacitor/camera plugin. The current implementation is as follows: await Camera.getPhoto({ quality: 100, allowEditing: true, resultType: CameraResultType.Base64, source: CameraSo ...

"Using Angular's NgFor directive to efficiently organize and collapse data within

I am currently working on displaying API data in a table using ngFor, and I am facing an issue with hiding/showing a specific row of details outside the ngFor loop. Since this line is not within the ngFor loop, I am unable to bind the data accordingly. Can ...

Ways to conceal all rows in Ag-grid during data loading

Currently, I am utilizing "ag-grid-angular": "^25.3.0" along with "ag-grid-community": "^25.3.0" As I fetch data from the server, I encounter an issue where an empty row briefly appears right before the grid is rend ...

Encountering an issue with importing mongoose models while trying to create a library

I've been working on creating a library of MongoDB models and helper classes to be shared as an npm module with the rest of my team. However, I'm facing an issue with the main code that I import from lib MongoConnector which processes configurati ...

Having trouble with 'npm <script-command>' not working? Try changing it to 'npm run-script <script-command>' instead

Currently, I am configuring a node js backend to operate on TS for the first time within a mono-repo that has a specific folder structure. You can view the structure here. The package.json file is located in the main directory as shown below: "scr ...

Achieve Full Height with Bootstrap 4!

I have gone through numerous threads on this issue and attempted all the suggestions, but nothing seemed to work for me. Here is the code I am currently using: <div class="container-fluid d-flex flex-column" style="height: 1 ...

Enhanced security and performance through HTTP interceptor with Authentication and Cache

Currently working on a website for a school project and I have successfully implemented an Authentication HTTP interceptor. Each user now has a session established. However, I am facing an issue with caching some requests. I tried searching for tutorials ...

"Customizing API requests based on specific conditions with n

For a specific scenario, I need to login as an admin in one case and as a regular user in another. signIn$ = createEffect(() => this.actions$.pipe( ofType(AuthActions.signInRequest), exhaustMap(({ variables, redirectTo, hasAdmin }) =&g ...

Synchronizing Events across Two JavaScript Applications

In my game app (using Electron) and web app (testing on Android Chrome), they communicate through a websocket server to coordinate a countdown. I've noticed that in environments with low latency, the synchronization is fine. However, when there is mor ...

When using AngularJS 2, the class identity is lost when resolving a Promise during fetching

SUMMARY: I'm encountering an issue where I am fetching Object instances instead of Org instances from my data in Angular 2. Is there a way to retrieve Org objects directly or is this the expected behavior? DETAILS: In my Angular 2 project, I have mod ...

Is it necessary to provide initialState in React Context when using useState in TypeScript, even if it serves no purpose?

Using Context to share the value and setValue from the useState hook. The code provided below is functional, but it may be considered overly verbose. As a TypeScript beginner, I am wondering if there is a more elegant approach to achieve the same functiona ...