【问题标题】:Cannot read property 'content' of undefined Angular无法读取未定义 Angular 的属性“内容”
【发布时间】:2020-03-21 16:36:30
【问题描述】:

我在我的组件中执行正常的 http get 请求,并在 html 中显示结果,一切正常,但是当我打开控制台时出现错误。 '无法读取未定义的属性'内容'。

<div class="container myPadding">
<div class="form-row justify-content-center">
    <h1>Substances</h1>
</div>

<div class="form-row justify-content-center">
    <p class="alert alert-info">
        Total Substances registered: ({{ substanceList.totalElements }})
    </p>
</div>
<a>
    <table class="table table-striped table-bordered" style="width:100%">
        <thead>
            <tr>
                <th>ID</th>
                <th>Substance Name</th>
            </tr>
        </thead>
        <tbody *ngFor="let response of substanceList.content | slice:0:99">
            <tr>
                <td>{{response.neo4jId}}</td>
                <td>{{response.substanceName}}</td>
            </tr>
        </tbody>
    </table>
</a>

和ts文件

export class SubstancesComponent implements OnInit, OnDestroy {
substanceList: any;
subscription: Subscription;

constructor(private http: HttpClient, private drugService: DrugsService) { }

ngOnInit() {
  this.getAllSubstances();
}

getAllSubstances() {
 this.subscription = this.drugService.getSubstances().subscribe(response => {
  this.substanceList = response;
  console.log(this.substanceList);
})
}

ngOnDestroy() {
 this.subscription.unsubscribe();
 }

}

这是我的服务中的功能

    getSubstances(): any {
    return this.http.get(environment.substancesUrl);
}

浏览器中的结果是我想要的结果,但是这个错误出现在控制台中,我想了解为什么会出现这个错误以及如何解决这个问题。

【问题讨论】:

  • 有人在.cmets 中提到了类似的消息:stackoverflow.com/questions/45808908/…“它与导入文件的拼写错误有关”您必须截取整个消息或复制/粘贴它以某种方式更加确定。
  • 内容是您响应的属性?您是否使用 *ngFor 在您的 html 上呈现数据?

标签: angular


【解决方案1】:

您不能直接访问 HTML 页面中对象的元素。

请进行以下更改:

  <tbody *ngFor="let response of substanceList && substanceList.content | slice:0:99">

  <tbody *ngFor="let response of substanceList?.content | slice:0:99">

【讨论】:

  • @TsolakidisKonstantinos 感谢您的回复和测试。我很高兴你的问题得到了解决。也谢谢你。
【解决方案2】:

您想在所有对象属性前添加?s,例如{{ substanceList?.totalElements }} 可防止与尝试在 get 请求仍在返回的对象上查找密钥 totalElements 相关的问题。

您可能还希望将异步管道添加到由于异步调用而填充的任何变量,以确保数据仅在可用时才呈现到屏幕上(并且不会短暂显示undefined for示例),例如{{ substanceList?.totalElements | async }}

【讨论】:

  • 我在我的 ts 文件中进行异步调用,因为我订阅了,所以不需要 html 中的异步 PIPE,?正在做这项工作。这可能意味着,不要关心类型。
猜你喜欢
  • 2018-01-30
  • 2017-11-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-01-12
  • 2015-09-08
  • 2016-05-12
  • 2019-07-25
相关资源
最近更新 更多