错误类型错误:无法读取未定义的属性“0”

时间:2021-07-24 03:45:24

标签: javascript json angular

我正在使用 angular,我想从以下 json 对象打印所有字段

[
    {
        "id": 1,
        "name": "Oasis Technology",
        "title": "Fill like getting water in destert",
        "email": "thorataniket777@gmail.com",
        "Phone": "7741091028  , 7774966527",
        "instagram": "https://instagram.com/",
        "linkedin": "https://www.linkedin.com/",
        "youtube": "https://youtube.com/"
    }
]

角度代码 .TS 文件

export class HeaderComponent implements OnInit {
  public details:any
  url="http://127.0.0.1:8000/aboutus/?format=json"
  constructor(private http: HttpClient, private route :Router){
     this.http.get(this.url).toPromise().then(data=>{
       console.log(data)
      this.details=data
      
     });  
    }

.html 文件

<div class="p-5 text-center bg-light bg" style="height: 300px;" >
      <h1 class="mb-3"><span style="color: white;">Welcome to</span> <span style="color:gold;"> {{details[0].name}}</span></h1>
      <h4 class="mb-3"></h4>
      <h2 style="color: white;">{{details[0].title}}t</h2>

但是我在浏览器控制台中收到错误

core.js:6456 ERROR TypeError: Cannot read property '0' of undefined
    at HeaderComponent_Template (header.component.html:7)
    at executeTemplate (core.js:9575)
    at refreshView (core.js:9441)
    at refreshComponent (core.js:10612)
    at refreshChildComponents (core.js:9238)
    at refreshView (core.js:9491)
    at refreshComponent (core.js:10612)
    at refreshChildComponents (core.js:9238)
    at refreshView (core.js:9491)
    at renderComponentOrTemplate (core.js:9555)

2 个答案:

答案 0 :(得分:0)

这个API调用
this.http.get(this.url).toPromise() 是一个异步任务,因此当您的应用呈现 HeaderComponent 时,此属性 public details:any 未定义,因此模板中的 details[0] 将创建 Err 无法读取未定义的属性“0” 您可以使用 *ngIf like 来解决此问题:

<div *ngIf="details && details.length"
 class="p-5 text-center 
 bg-light bg"
 style="height: 300px;">
 <h1 class="mb-3">
     <span style="color: white;">Welcome to</span>
     <span style="color:gold;">{{details[0].name}}</span>
 </h1>
 <h4 class="mb-3"></h4>
 <h2 style="color: white;">{{details[0].title}}t</h2>

答案 1 :(得分:0)

<div class="p-5 text-center bg-light bg" style="height: 300px;" *ngIf="details.length>0">
          <h1 class="mb-3">
            <span style="color: white;">Welcome to</span> <span          
            style="color:gold;">{{details[0]?.name}}</span>
          </h1>
          <h4 class="mb-3"></h4>
          <h2 style="color: white;">{{details[0]?.title}}t</h2>
</div>