Search code examples
jsonangularhttpangular7

Angular 7: ERROR TypeError: Cannot read property '0' of undefined (But result is working)


I have a problem that my console shows an error * "ERROR TypeError: Cannot read property 'bg_img_preview' of undefined*. But the result is ok I can get my data to show. I am not sure, why It shows an error event I can get my data. I notice that console.log doesn't show the result either. I am using Angular 7 and creating a service HTTP client to get data from the JSON file in my local.

This is service

   import { Injectable } from '@angular/core';
   import { HttpClient } from '@angular/common/http';

   @Injectable({providedIn: 'root'})
   export class HttpGetJsonService {

   private _careerUrl = 'assets/json/careers-page.json';

   constructor(private _HttpClient: HttpClient) { }

    getCareerData() {
     return this._HttpClient.get(this._careerUrl);
     }

   }

This is career.ts

   import { Component, OnInit } from '@angular/core';
   import { HttpGetJsonService } from '../../../shared/http-service/http- 
            get-json.service';

   @Component({
   selector: 'app-career-pages',
   templateUrl: './career-pages.component.html',
   styleUrls: ['./career-pages.component.scss']
   })
   export class CareerPagesComponent implements OnInit {
    section: any = {};
    constructor(private _HttpGetJsonService: HttpGetJsonService) { }

   ngOnInit() {

    this._HttpGetJsonService.getCareerData().subscribe(data => {
    this.section = data['data'][0].all_sections;
    console.log(this.section);
    })
   }
   }

This is career.html

    <div class="col-md-4">
            <img [src]="section[2].bg_img_preview" alt="" width="50%">
     </div>

This is JSON file

    ...........
    ...........
    {
      "id": "sec61539669775971",
      "name": "career-asset",
      "type": null,
      "bg_img": "/assets/img/faq-bg/faq-bg-01.jpg",
      "bg_color": null,
      "created_date": null,
      "updated_date": null,
      "bg_video": null,
      "created_by_id": "usr01539232275296",
      "updated_by_id": "usr01539232275296",
      "is_backup": 0,
      "parent_id": null,
      "ordering": 1,
      "edit_bg_image": 1,
      "site_pages_id": "sitePagesec315395",
      "record_type": "asset",
      "bg_img_preview": "/assets/img/faq-bg/faq-bg-01.jpg",
      "langs": [],
      "sub_sections": [],
      ............
      ............

The result is ok. I can get my picture but I am wondering why I get that error? Even console.log also doesn't show the picture value. I am very new to this.


Solution

  • You can try:

    [src]="section[2]?.bg_img_preview"
    

    Your section[2] object doesn't have the value until the API response arrives. So use ? to apply the null check until the response arrives.