Angular Typescript subscription value is null even though the template still receives the data

As a newcomer to Angular and Typescript, I've encountered a peculiar issue. When trying to populate a mat-table with values retrieved from a backend API, the data appears empty in my component but suddenly shows up when rendering the template.

Here's an example of my component:


import { Component, OnInit, ViewChild } from '@angular/core';
import { first } from 'rxjs/operators';
import { MatTableDataSource } from '@angular/material/table';
import { MatPaginator, MatSort } from '@angular/material';

import { Invoice } from '../_models';
import { InvoiceService } from '../_services';

@Component({
  selector: 'app-invoices',
  templateUrl: './invoices.component.html',
  styleUrls: ['./invoices.component.css']
})
export class InvoicesComponent implements OnInit {
  displayedColumns=['rating', 'amount', 'debtor', 'serial', 'dateout', 'expiration', 'daysleft', 'fid']
  invoices: Invoice[] = [];
  dataSource= new MatTableDataSource<Invoice>(this.invoices);

  @ViewChild(MatPaginator) paginator: MatPaginator;
  @ViewChild(MatSort) sort: MatSort;

  constructor(
    private invoiceService: InvoiceService
  ) { }

  ngOnInit() {
    this.loadInvoices();
    console.log(this.invoices);
    this.dataSource.paginator = this.paginator;
    this.dataSource.sort = this.sort;
  }
  private loadInvoices(){
    this.invoiceService.getUserInvoices().pipe(first()).subscribe(invoices => {
      this.invoices=invoices;
    });
    console.log(this.invoices);


  }
  applyFilter(filterValue: string) {
    filterValue = filterValue.trim(); // Remove whitespace
    filterValue = filterValue.toLowerCase(); // Datasource defaults to lowercase matches
    this.dataSource.filter = filterValue;
    if (this.dataSource.paginator) {
      this.dataSource.paginator.firstPage();
    }
  }

}

And here is a snippet from the template:


...

@foreach($invoices as $invoice)
...
@endforeach

...

The key point of concern lies in the usage of [dataSource]="invoices". Upon retrieving data via the loadInvoices method, the array remains empty. Switching it to [dataSource]="dataSource" also results in an empty array. How can I effectively utilize the fetched data to initialize a MatTableDataSource object and pass it to the template?

With assistance from @DiabolicWords, the updated component code looks like this:


// Updated component code

Answer №1

If you're struggling with the timing of values returning from an Observable and your console.log()-calls are firing before the data is actually populated, there's a simple fix to ensure you display the correct information. Give this approach a try:

 ngOnInit() {
   this.loadInvoices();
 }

 private loadInvoices(){
   this.invoiceService.getUserInvoices().pipe(first()).subscribe(invoices => {
     this.invoices=invoices;
     console.log(this.invoices);
     this.dataSource = new MatTableDataSource<Invoice>(this.invoices); 
     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 looking for a way to convert the date format from "yyyy-MM-dd" to "dd-MM-yyyy" in NestJs

I need help with changing the date format from "yyyy-MM-dd" to "dd-MM-yyyy". Currently, my entity code looks like this: @IsOptional() @ApiProperty({ example: '1999-12-12', nullable: true }) @Column({ type: 'date', nullable: true } ...

Encountering Problems with Ajax Refresh During Page Initialization

I'm currently experiencing issues with loading content on page load using ajax. The ajax is successfully calling the correct action in the corresponding controller. The initial part of the action code, where I update the database, is functioning as ex ...

Having difficulty using the Angular 6 "generic type elementref requires 2 type arguments" error message in my code

When attempting to use ElementRef, I included the following import statement: import { Component, OnInit, ElementRef, ViewChild } from '@angular/core'; I followed the examples and injected it into the constructor as shown: constructor(private ...

A blank canvas emerges upon utilizing the Angular-Bootstrap Carousel feature

This is my first experience using Angular with Bootstrap's carousel component, and I'm encountering a peculiar issue where a white slide appears before each transition (refer to the GIF below). Despite following the setup instructions on ng-boots ...

Encountered a 404 error while using a MEAN stack application

Encountering a 404 error while attempting to post data using Postman in Chrome. Any assistance will be greatly valued. I am following the application from this link: https://www.youtube.com/watch?v=wtIvu085uU0 Here is the code snippet: //importing modul ...

Leverage elements from nearby npm repository when building an Angular 2 application

After developing a generic chart component using d3 and Angular 2, I decided to share it by publishing it in a local npm repository. This way, anyone can easily incorporate the chart component into their Angular project by simply running the npm install my ...

Subscribing to a GraphQL mutation through Angular with the Appsync client

Currently, I am developing a chat application in Angular using GraphQL with Appsync on AWS. The current process for creating a new chat involves mocking up the chat and sending it to the server. On the server-side, a unique chat_id is generated for each ch ...

Using the spread operator in Typescript with an object that contains methods

Within my Angular project, I am faced with an object that includes a type and status field where the status can change depending on the type. While some might argue that this is not the best design practice, it is how things are currently structured in my ...

Refresh Panel ASP.NET 1.1

I am working on a web application page using ASP.NET 1.1 and .NET framework 1.1. The data is displayed in a GridView. I am looking for a way to update the data when multiple items are selected without a full page postback. Any suggestions or help would be ...

TypeScript allows for the declaration of a function that includes a mandatory property within the function signature

If I desire a tagged function with an interface such as: interface TaggedFun { (args): void; tag: boolean; } It appears that declaring a function to match this signature is not possible (since any function literal will lack the mandatory tag prop ...

Issue encountered while transferring data using Ajax

I am a novice in the realm of ajax and currently immersed in a project that demands passing data from an ajax function to a php page for the purpose of dynamically generating and displaying modals. Although I am successful in creating the modal, I suspect ...

Making the Decision: WPF vs. Silverlight

We currently have a web application built with ASP.NET/Ajax and are considering transitioning it to either WPF or Silverlight. Is anyone able to provide a comparison of these two technologies in terms of productivity, performance, maintainability, trade-o ...

TS2365: The '!== 'operator is not compatible with the types ""("" and "")""

function myFunction(identifier: string) { identifier = "("; }; let identifier: string = ")"; if (identifier !== '(') throw "Expected '(' in function"; myFunction(identifier); if (identifier !== ')') throw "Expected &a ...

The Azure function encounters an AuthorizationFailure error while attempting to retrieve a non-public file from Azure Blob Storage

Within my Azure function, I am attempting to retrieve a file from Blob Storage labeled myappbackendfiles. The initial code (utils/Azure/blobServiceClient.ts) that initializes the BlobServiceClient: import { BlobServiceClient } from "@azure/storage-bl ...

Issue: ASP.NET encountered a Sys.WebForms.PageRequestManagerServerErrorException error

I am facing an issue with my AJAX TabContainer placed within an update panel. The menus are not switching properly; they remain on the same page. Upon checking, I found this error in JavaScript: https://i.stack.imgur.com/OsjMg.png Is there a way to pinpoi ...

Using Angular 5 with Typescript to generate and return an array of freshly instantiated typed objects

My backend service provides me with "moments," and I have two functions to handle this data. One is a get() method that returns a single object, and the other is a search() method that returns an array of objects. moment.service.ts The get method success ...

Issue with Angular data display in template

My Ionic app with Angular is fetching data in the constructor, but I am facing difficulties displaying it in the HTML. Code component receiver: any; constructor( //.... ) { // get receiver data const receiverData = this.activatedRoute.snapsho ...

Error message: In my router module, Angular's 'Subject' is not subscribed to

Currently, I am utilizing a canActivateFn guard in my application where I am subscribing to a Subject. This particular Subject was instantiated in a separate service, and I'm perplexed as to why the subscription does not seem to trigger (the callback ...

Exploring the Benefits of Using JSON in AJAX Requests

Can you help me determine the best way to extract data from a php page using ajax in the form of a json array? Here is an example code snippet: $.ajax({ type: "get", url: "assets/update_cart_user_fstore.php", data: up, cache: false, su ...

How can I effectively utilize the Angular router to share routes among various named outlets?

My application requires displaying the same components or routes in multiple areas of the interface. This means allowing users to show certain components in various locations based on their selection, such as side panels or bottom right panels. In my situ ...