所以我正在我的 MEAN-stack 应用程序中开发一个论坛,并且我从我的 node.js 后端请求了这些部分。我能够从后端接收我想要的内容,但是当我想显示检索到的 4 个部分时,我无法使行显示在屏幕上。我在我的子论坛上做了同样的机制,它似乎在那里工作,但我不明白是什么让它不起作用。
我的论坛模板 (forum.component.html)
<div class="row justify-content-center mb-3 mt-5">
<div class="col-md-8">
<table class="table">
<thead>
<tr>
<th>Forum</th>
<th>Posts</th>
<th>Replies</th>
<th>Last Post</th>
</tr>
</thead>
<tbody>
<tr *ngFor="let section of sections" [routerLink]="section.name">
<td>
<p><b>{{section.name}}</b></p>
<p>For all general topics of Wizards Unite.<br> Ask a question or open a topic te contribute to the community.</p>
</td>
<td>{{section.posts.length}}</td>
<td>{{section.totalReplies}}</td>
<td>
<p>{{section.lastPost.title}}</p>
<p>by {{section.lastPost.name}} on {{section.lastPost.date | amDateFormat:'LL'}}</p>
</td>
</tr>
</tbody>
</table>
</div>
<div class="col-md-2 side-column">
</div>
</div>
我的论坛组件 (forum.component.ts)
import {Component, OnInit} from "@angular/core";
import {ForumService} from "./forum.service";
import {ActivatedRoute} from "@angular/router";
@Component({
selector: 'forum',
templateUrl: 'forum.component.html',
styleUrls: [
'forum.component.css'
]
})
export class ForumComponent implements OnInit {
sections = [];
constructor(private forumService: ForumService, private route: ActivatedRoute){}
ngOnInit(){
this.forumService.getSections()
.subscribe(function (sections:any) {
this.sections = sections.obj;
console.log(this.sections);
})
}
}
这是我从组件中的 getSections() 函数收到的数据。乍一看,一切都如我所愿,但正如您所看到的,行没有出现在屏幕的左侧*
最佳答案
当调用回调函数时,this
的上下文通常会发生变化。
在您的示例中,this
不再引用该类,因此它没有按照您的预期设置sections
。
将函数(sections:any)
更改为(sections:any)=>
。通过使用箭头函数,它应该保留其上下文
关于javascript - ngFor 不适用于 <tr> 元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50399322/