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

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

我有一个问题,我的控制台显示错误 * "ERROR TypeError: Cannot read 属性 'bg_img_preview' of undefined*。但结果是好的,我可以显示我的数据。我不确定,为什么它显示错误事件我可以获取我的数据。我注意到 console.log 也没有显示结果。我正在使用 Angular 7 并创建一个服务 HTTP 客户端以从我本地的 JSON 文件中获取数据。

这是服务

   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);
     }

   }

这是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);
    })
   }
   }

这是career.html

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

这是JSON文件

    ...........
    ...........
    {
      "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": [],
      ............
      ............

结果还可以。我可以得到我的照片,但我想知道为什么会出现该错误?即使 console.log 也不显示图片值。我对此很陌生。

你可以试试:

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

您的 section[2] 对象在 API 响应到达之前没有值。因此,使用 ? 应用空检查,直到响应到达。