首页 > 解决方案 > 带有 *ngFor 的 Angular 视图不渲染数据

问题描述

我是 Angular 的新手,但熟悉 Javascript。

我正在为演示设置 CRUD,但无法让此列表循环遍历从我们的 API 返回的数据。

数据加载正常,我可以在控制台中看到它。但是*ngFor下面没有呈现任何<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();
    }
}

就像我说的,数据显示在控制台中,所以我认为它必须在视图中。

标签: javascriptangularlambdaarrow-functions

解决方案


尝试这个:

在 ts 文件中:

getPagesFromView() {
    If (this.pages.length > 0) {
        return this.pages;
    }
}

推荐阅读