html - Angular中的“字符串”ngFor类型不存在属性“名称”
问题描述
尝试显示对象数组时出现此错误
Error: src/app/components/timeline/timeline.component.html:9:29 - error TS2339: Property 'name' does not exist on type 'string'.
<h4>{{publication.user.name}}</h4>
~~~~
src/app/components/timeline/timeline.component.ts:10:15
10 templateUrl: './timeline.component.html',
~~~~~~~~~~~~~~~~~~~~~~~~~~~
Error occurs in the template of component TimelineComponent.
在我的timeline.component.html 我有这个:
<div id="publications">
<div *ngFor = "let publication of publications" class="item-publication">
<div class="panel panel-default">
<div class="panel-body">
<h4>{{publication.user.name}}</h4>
</div>
</div>
</div>
</div>
这是我拥有的 getPublications 函数
getPublications(page){
this._publicationService.getPublications(this.token, page).subscribe(
response => {
console.log(response);
if(response.publications){
this.total = response.total_items;
this.pages = response.pages;
this.publications = response.publications;
if(page > this.pages){
this._router.navigate(['/home']);
}
}else{
this.status= 'error';
}
},
error =>{
var errorMessage = <any>error;
console.log(errorMessage);
if(errorMessage != null){
this.status = 'error';
}
}
);
}
如果我创建一个 console.log(response),它会向我显示数组的值和属性是否正确(姓名、姓氏、电子邮件、文本等)
在 HTML 代码中,当我对出版物的文本进行循环时,<h4>{{publication.text}}</h4>
它可以工作,即使我使用<h4>{{publication.user}}</h4>
它也会显示一个对象列表。
我正在上一门在线课程,基本上是逐行复制老师所做的,但是 IDK 为什么当我尝试显示姓名和姓氏属性时,它会显示我告诉你的错误
谢谢您的帮助。
解决方案
我找到了解决方案,并且与TS 类型系统有关,所以基本上我有一个名为的模型对象publication.ts
,其中包括:
export class Publication{
constructor(
public _id:string,
public text: String,
public file: String,
public created_at: String,
public user: String
){}
}
问题与属性的类型有关,user
因此通过将其类型更改为public user: any
有效,现在它显示了必填字段。很抱歉在寻求帮助之前没有深入搜索就发布了这个。新手错误
谢谢您的帮助
推荐阅读
- java - 创建 Spring Boot Otka 资源服务器时出现异常
- r - 无法绘制数据子组的均值
- python - 如何以不同的方式更新屏幕的字体?
- javascript - 如何将来自 URL 的参数值作为变量插入到 Google Analytics(分析)代码中?
- java - 如何使用来自 foreach 的被调用函数的返回值
- node.js - 从 Google Cloud Storage 流式下载图像时如何正确设置响应标头
- javascript - 基于当前 URL 问题的主动导航类
- php - 如何在phpspreadsheet中使用linest函数?
- swift - 对 .map 变换闭包的困惑
- system-verilog - Verilog 流水线乘法器直觉