Home > Enterprise >  Why does console give errors after fetching data from API Angular
Why does console give errors after fetching data from API Angular

Time:10-27

I'm fetching data from API and want to display tabs for each object value. Everything works fine, just getting error in the console. Cannot read properties of undefined (reading 'Projects') Data is displaying correctly as it should. I'm assuming it cannot read it at first so it says it's undefined. And after fetching data appears.

How should I get rid of this error?

HTML:

<mat-tab *ngFor="let object of projects.Projects; let i = index" label="{{ object.Id }}"></mat-tab>

Component:

import { Component, OnInit } from '@angular/core';
import { TablesService } from "../tables/tables.service";

@Component({...})

export class MyComponent implements OnInit {
  projects: any;
  constructor(public tableService: TablesService)
  {
    this.tableService.fetchAPI().subscribe((data) => {
      this.projects = data;
    })
  }

  ngOnInit(): void {
  }

}

CodePudding user response:

This is happening because projects is only declared and not initialized, so until your API call is completed and you put some data in that variable, it will be undefined. One way to deal with this is to assume that projects could be undefined and use the ? (optional chaining operator) to account for that:

<mat-tab *ngFor="let object of projects?.Projects; let i = index" label="{{ object.Id }}"></mat-tab>

Another solution could be to give an initial value to the projects property:

projects: any = {};

CodePudding user response:

The template will be rendered before the server has responded

So here, projects will be temporarily undefined

<mat-tab *ngFor="let object of projects.Projects; let i = index" label="{{ object.Id }}"></mat-tab>

You can use an *ngIf to prevent this part being rendered until projects is defined. But, as you can put only one structural operator, you will have to add a ng-container around it :

<ng-container *ngIf="projects">
  <mat-tab *ngFor="let object of projects.Projects; let i = index" label="{{ object.Id }}"></mat-tab>
</ng-container>

Or you can also add a ? after projects, like this :

<mat-tab *ngFor="let object of projects?.Projects; let i = index" label="{{ object.Id }}"></mat-tab>

  • Related