Reputation: 2610
So I'm working on a forum in my MEAN-stack app and I requested the sections from my node.js back-end. I was able to receive what I want from the back-end, but when I want to display the 4 sections I retrieved I am unable to make the rows appear on my screen. I did the same mechanism on my sub-forums and it does seem to work there, but I don't see what's making this not work.
My forum template (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>
my forum component (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);
})
}
}
Here is the data that I received from the getSections() function in my component. On first sight everything is as I desire, but as you can see the rows do not appear on the left side of the screen *
Upvotes: 0
Views: 1417
Reputation: 18271
When a callback function is invoked, often the context of this
will change.
In your example, this
is no longer referring to the class, so it's not setting the sections
as you're expecting.
Change function (sections:any)
to (sections:any) =>
. By using an arrow function, it should retain its context
Upvotes: 4