0

I'm new to Angular, but familiar with Javascript.

I'm setting up a CRUD for a demo and can't get this list to loop over data returned from our API.

The data is loading fine, I can see it in the console. But the *ngFor below does not render any <li>s.

pages.component.html:

<div class="row">
    <div class="col-sm-4">
        <p>Pages</p>
        <ul>
            <li *ngFor="let page of pages">
                {{page.Name}}
            </li>
            <li>this shows up.</li>
        </ul>
    </div>
</div>

pages.component.ts:

import { Component, OnInit } from '@angular/core';
import { PageService } from '../page.service';
import { Page } from '../page';

@Component({
  selector: 'app-pages',
  templateUrl: './pages.component.html',
  styleUrls: ['./pages.component.css']
})
export class PagesComponent implements OnInit {
    pages: Page[];

    getPages(): void {
        this.pageService.all().subscribe(function(pages) {
            console.log(pages);
            this.pages = pages;
        }
    }

    constructor(private pageService: PageService) { }

    ngOnInit() {
        this.getPages();
    }
}

Like I said, the data shows up in the console, so I think it must be in the view.

Joe Flynn
  • 6,908
  • 6
  • 31
  • 44

3 Answers3

0

It was in the TS after all.

My getPages function was using a lambda instead of an arrow-function. I thought they were semantically identical. But the lambda was not properly bound to this.

So when I wrote to this.pages it was not saving to the component's pages member, rather the anonymous function itself.

getPages(): void {
    this.pageService.all().subscribe(function(pages) {
        this.pages = pages;
    }
}

Should be this instead:

getPages(): void {
    this.pageService.all().subscribe(pages => this.pages = pages);
}
Joe Flynn
  • 6,908
  • 6
  • 31
  • 44
0

Try this:

In ts file:

getPagesFromView() {
    If (this.pages.length > 0) {
        return this.pages;
    }
}
Sumit Vekariya
  • 482
  • 2
  • 12
0

The problem is inside the subscribe callback the context of this is different. So you can either use arrow function or bind & pass the context of this

getPages(): void {
        this.pageService.all().subscribe(function(pages) {
            console.log(pages);
            this.pages = pages;
        }.bind(this))
    }
brk
  • 48,835
  • 10
  • 56
  • 78