Ways to maintain data returned by forkJoin

I encountered a situation where I needed to retrieve results from 2 HTTP calls and combine them into an array that would be passed to a class instantiation. Below is the code snippet:

export class VideoListComponent implements OnInit {
  @ViewChild(MatPaginator) paginator: MatPaginator;
  @ViewChild(MatSort) sort: MatSort;
  dataSource: VideoListDataSource;
  constructor( private http: HttpProxyService, private videoService: VideoService ) { }
  /** Columns displayed in the table. Columns IDs can be added, removed, or reordered. */
  displayedColumns = ['Video Name', 'Author', 'Category Name', 'Highest Quality Format', 'Release Date', 'Options'];

  ngOnInit() {
    let observables = [this.videoService.getInitialData('movie-authors'), this.videoService.getInitialData('movie-categories')];
    forkJoin(observables).subscribe(res => {
      this.dataSource = new VideoListDataSource(this.paginator, this.sort, res);
      console.log(this.dataSource);
    })
  }

}

While this.dataSource appears as expected in the console log, it is being flagged as undefined when used in the HTML template.

Any suggestions? Is there something crucial that I may have overlooked?

Updated with HTML markup

<div class="mat-elevation-z8">
  <table mat-table class="full-width-table" [dataSource]="dataSource" matSort aria-label="Elements">
    <!-- Id Column -->
    <ng-container matColumnDef="id">
      <th mat-header-cell *matHeaderCellDef mat-sort-header>Id</th>
      <td mat-cell *matCellDef="let row">{{row.id}}</td>
    </ng-container>

    <!-- Name Column -->
    <ng-container matColumnDef="name">
      <th mat-header-cell *matHeaderCellDef mat-sort-header>Name</th>
      <td mat-cell *matCellDef="let row">{{row.name}}</td>
    </ng-container>

    <tr mat-header-row *matHeaderRowDef="displayedColumns"></tr>
    <tr mat-row *matRowDef="let row; columns: displayedColumns;"></tr>
  </table>

  <mat-paginator #paginator
      [length]="dataSource.data.length"
      [pageIndex]="0"
      [pageSize]="50"
      [pageSizeOptions]="[25, 50, 100, 250]">
  </mat-paginator>
</div>

Answer №1

Revise your code as shown below:

<div class="mat-elevation-z8">
  <table *ngIf="data" mat-table class="full-width-table" [dataSource]="data" matSort aria-label="Items">
  </table>   
     ......
</div>

Why isn't my code working :

The issue is that you are trying to display table data using a data variable that has not been initialized. The data variable retrieves its value from a service. Since the view loads before the service call is made and at that point, data is undefined, it results in an error.

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

How can I extend a third-party JavaScript library in TypeScript using a declaration file?

Currently, I am working on creating a .d.ts file for an external library called nodejs-driver. While I have been able to map functions and objects successfully, I am struggling with incorporating the "inherit from objects defined in the JS library" conce ...

Retrieve data from the database and dynamically populate a dropdown list based on the selection made in another dropdown menu

I created a JSP page where the values of the second dropdown should change based on the selection in the first dropdown. Both dropdown values are retrieved from the database. The values for the second dropdown are fetched using the foreign key from the t ...

Guide on setting up multiple Axios instances in NestJS

I'm in the process of migrating an existing Express application to NestJS. Currently, I have a configuration file where I define multiple axios instances for each microservice: export const writeModelApi = axios.create({ baseURL: getWriteModelApiUrl ...

What is the reason for parsing JavaScript code when the page is first loaded?

I recently placed an Adsense (for content) code on my website in order to show a single ad: <script async src="//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"> </script> <ins class="adsbygoogle" style="display:inline-block;width ...

What could be causing the problem between typescript and Prisma ORM as I attempt to locate a distinct item?

I'm encountering a problem with using the prisma .findUnique() function. Even though my code doesn't display any compilation errors, attempting to access a product page triggers a runtime error. PrismaClientValidationError: Invalid `prisma.produ ...

Tips for isolating the filtering process to a specific search box in Angular, rather than filtering the entire dataset

I have a collection of data with individual search boxes, but when I enter information in one search box, it gets applied to all search boxes. I want to be able to filter the data in specific search boxes. Code Snippet: <div *ngFor="let item of data"& ...

What is the best way to integrate AJAX with a confirmation button?

Hey there, I'm currently working on implementing an AJAX URL in a confirmation button to update something in the database. In the JavaScript section, I have the following code: function freeze_account() { $.confirm({ title: 'Confirm ...

Every time I hit the refresh button, I find myself forcefully logged out

After switching from using localStorage to cookies in my React JS web app, I am experiencing an issue where I get logged out whenever I refresh the page. Even though the cookies are still stored in the browser, the authentication process seems to be failin ...

Prevent a TypeScript generic object from containing a specific property

I've encountered a situation where I need to create a generic function that accepts an object as a parameter, but with the condition that the object cannot have properties in the format __property__. Currently, my approach is: type RemoveProps = { ...

Tips for Uploading Large Images to Backend API in Next.js

As I work on building my portfolio using NextJS, I encountered an issue with the Project Functionality. When converting images to base64 and sending them to an API for uploading on Cloudinary, everything runs smoothly as long as the total size of the req ...

Expanding Body Content in Bootstrap Modal for Full Width Display

I am currently working on implementing a 'zoom' feature on my webapp that involves transferring a (Google) chart into a modal. However, I would like the chart to automatically expand and fit the full width of the modal. This is the structure of ...

Angular-fontawesome icons are experiencing issues with their background color not scaling properly

Currently utilizing angular-fontawesome, I am seeking to alter the background color of a font-awesome fa-icon <fa-icon class="vue-icon" [icon]="faVue" ></fa-icon> To change the color, I modified the CSS using ...

Having difficulty maintaining the consistent size of the MathJax math font in relation to the surrounding text

Issue I am currently using MathJax to display mathematical equations on my webpage: https://i.sstatic.net/EfvVq.png The problem I am facing is that I want the math font to appear larger than the surrounding text, as depicted in the image above. However, ...

Combining two lists in immutable.js by flattening and zipping

When faced with two immutable lists, such as: const x = [5,6,7]; const y = [x,y,z,w]; Is there a straightforward method to combine/interleave them in order to obtain: const z = [5,x,6,y,7,z,w]; ...

Exploring Vue and Nuxt JS: What Causes the Issue of Unable to Create the Property 'display' on the String 'bottom:30px;right:30px;'

this piece of code is designed for a component that allows users to jump back to the top of the page. However, after refreshing the page, it stops working and throws an error. The project uses the Nuxt and Vue framework. Can anyone identify the reason behi ...

Angular developers may encounter a dependency conflict while attempting to install ngx-cookie

I'm currently facing an issue while attempting to add the ngx-cookie package for utilizing the CookieService in my application. Unfortunately, I am encountering some dependency conflicts that look like the following: $ npm install ngx-cookie --save np ...

Transferring information between components is made easy with ng-content

In my application, I have a set of components that are used to create cards: <app-card-container> <app-card-title>Card title</app-card-title> <app-card-body> // some content </app-card-body> </app-card-con ...

Creating a duplicate key in a JavaScript object that aligns with MongoDB's multiple search string rule: a step-by-step guide

I am attempting to utilize MongoDB for performing searches based on multiple search strings. Here is the format for executing a search with multiple strings in MongoDB: db.meals.find({ $and: [ { mealName: /fish/ }, { mealName: /rice/ }, { mealName: /spicy ...

React's constructor being invoked twice

As a newcomer to react, I am in the process of developing a simple web application but encountering an issue. It seems like my Constructor is being called twice when I load a class component. Can anyone provide some assistance? Home.js import React from ...

Guide to implementing setTimeout in a .map() function in ReactJS

I am currently working on a project that involves an array of players. Whenever a user adds a new player to this array, I need it to be displayed one at a time with a 500ms interval between each player. Below is the code snippet I have written for this f ...