【问题标题】:Angular View with *ngFor Not Rendering Data [duplicate]带有 *ngFor 的角度视图不呈现数据 [重复]
【发布时间】:2019-03-18 05:25:57
【问题描述】:

我是 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();
    }
}

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

【问题讨论】:

    标签: javascript angular lambda arrow-functions


    【解决方案1】:

    毕竟是在 TS 中。

    我的 getPages 函数使用 lambda 而不是箭头函数。我认为它们在语义上是相同的。但是 lambda 没有正确绑定到 this

    所以当我写信给this.pages 时,它并没有保存到组件的pages 成员,而是匿名函数本身。

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

    应该改为:

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

    【讨论】:

      【解决方案2】:

      试试这个:

      在ts文件中:

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

      【讨论】:

        【解决方案3】:

        问题在于subscribe 回调内部this 的上下文不同。所以你可以使用箭头函数或bind & 传递 this 的上下文

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

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2017-08-04
          • 1970-01-01
          • 2020-03-08
          • 2017-08-25
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多