角度7:错误TypeError:无法读取未定义的属性“ 0”(但结果有效)

时间:2019-10-12 11:23:57

标签: json angular http angular7

我有一个问题,我的控制台显示错误 *“ ERROR TypeError:无法读取未定义的属性'bg_img_preview'* 。但是结果可以,我可以显示我的数据。不确定,为什么它显示错误事件我可以获取数据。我注意到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);
     }

   }

这是职业。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也不显示图片值。我对此很陌生。

1 个答案:

答案 0 :(得分:2)

您可以尝试:

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

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