typescript 使用打字稿访问数组的第一项,但浏览器返回未定义的属性

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/38779877/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-21 03:43:32  来源:igfitidea点击:

Using typescript to access first item of the array, but the browser return the property undefined

typescriptangular

提问by Charles

I write a getFooterContentmethod and i want to show data that through getFooterContent, but I have the following mistake:

我写了一个getFooterContent方法,我想通过 显示数据getFooterContent,但我有以下错误:

platform-browser.umd.js:1900

平台浏览器.umd.js:1900

ORIGINAL EXCEPTION: TypeError: Cannot read property 'content' of undefined

原始例外:类型错误:无法读取未定义的属性“内容”

getFooterContent(){
    return this.homepageService
                         .getFooter()
                         .then(content => this.footerContent = content)
                         .catch(error => this.error = error);
}

ngOnInit(){
    this.getFooterContent();
    console.log(this.footerContent);
}

and my html code

和我的 html 代码

<footer class="c-footer">
<div class="c-footer--service">
    <span>{{ footerContent[0].content}}</span>
    <span>{{ footerContent[1] }}</span>
</div>
<h1>{{ footerContent[2] }}</h1>
<div class="c-footer__version">
    <p>{{ footerContent[3] }}</p>
    <p>{{ footerContent[4] }}</p>
</div>

this.footerContentfirst prints []

this.footerContent第一次打印 []

and second prints

和第二次打印

[Object, Object, Object, Object, Object]
0:Object content:"253548" desc:"service_tel"

but i don't know why footerContent[0].contentreturns undefined?

但我不知道为什么footerContent[0].content返回未定义?

回答by Günter Z?chbauer

Like explained by @JukkaL

就像@JukkaL 解释的那样

<template [ngIf]="footerContent">
  <footer class="c-footer">
  <div class="c-footer--service">
    <span>{{ footerContent[0].content}}</span>
    <span>{{ footerContent[1] }}</span>
  </div>
  <h1>{{ footerContent[2] }}</h1>
  <div class="c-footer__version">
    <p>{{ footerContent[3] }}</p>
    <p>{{ footerContent[4] }}</p>
  </div>
</template>

回答by Arun Ghosh

You need to check if content exist:

您需要检查内容是否存在:

 <footer class="c-footer" *ngIf="footerContent.length > 4">
    <div class="c-footer--service">
        <span>{{ footerContent[0].content}}</span>
        <span>{{ footerContent[1] }}</span>
    </div>
    <h1>{{ footerContent[2] }}</h1>
    <div class="c-footer__version">
        <p>{{ footerContent[3] }}</p>
        <p>{{ footerContent[4] }}</p>
    </div>