首页 > 解决方案 > 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 为什么当我尝试显示姓名和姓氏属性时,它会显示我告诉你的错误

谢谢您的帮助。

标签: htmlangularngfor

解决方案


我找到了解决方案,并且与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有效,现在它显示了必填字段。很抱歉在寻求帮助之前没有深入搜索就发布了这个。新手错误

谢谢您的帮助


推荐阅读