申请* ngFor 只显示带有空数据的列表,同时从ngOnInit()上的api获取数据?

问题描述 投票:0回答:1

为了显示从Api获得的数据,我在li标签上应用了* ngFor指令。然后,我使用插值来显示li标签内的数据。但我没有在列表中获得任何数据。但是,该列表确实显示与从API获得的数据中可用的项目数完全相同的空列表项数。如果我在订阅方法浏览器中记录数据,则记录从api获取的数据,但是当我在订阅方法外记录数据时,浏览器会记录未定义的对象。我附上了我的密码。我将感谢任何形式的帮助和建议。

我尝试使用* ngIf条件,只有在数据已经在其他一个帖子中建议的ng的ngOnInit父ul标签中订阅时,才能使列表可见。

branch-list.component.ts

constructor(private service : BranchService) {  }
  ngOnInit() {
    this.service.getAll()
    .subscribe((data: Branch[]) => {
      this.branches = data;
      console.log(this.branches);
    });
    console.log(this.branches);
  };


branch-list.component.html

<ul class="list-group-flush" *ngIf="branches">
    <li *ngFor="let branch of branches; let serialNo = index" class="list-group-item">
      <span hidden>{{branch.Id}}</span>
      {{ serialNo+1 }}. {{ branch.BranchCode }} {{ branch.Description }}
    </li>
  </ul>
<ul>


console of browser

Angular is running in the development mode. Call enableProdMode() to enable the production mode.

undefined   

(7) [{…}, {…}, {…}, {…}, {…}, {…}, {…}]
0: {id: 1, branchCode: "KTM", description: "Kathmandu"}
1: {id: 2, branchCode: "PKH", description: "Pokhara"}
2: {id: 3, branchCode: "HTD", description: "Hetauda"}
3: {id: 4, branchCode: "MHN", description: "Mahendranagar"}
4: {id: 5, branchCode: "JHP", description: "Jhapa"}
5: {id: 6, branchCode: "KTM", description: "Kathmandu"}
6: {id: 7, branchCode: "PTN", description: "PTN"}
length: 7
__proto__: Array(0)

该列表应该显示控制台中记录的数据.Console按预期记录数据。但是在页面中,显示了空列表。空列表仅更新并显示序列号的值,但分支码和描述均为空白。

angular7 ngfor
1个回答
1
投票

最初设置branches = null;

而不是在ngOnInIt中执行API调用,而是尝试** ngAfterViewInit ** - 呈现DOM的位置

  ngAfterViewInit() {
    this.service.getAll()
    .subscribe((data: Branch[]) => {
      this.branches = [...data];
      console.log(this.branches);
    });
  };
<ul class="list-group-flush" *ngIf="branches && branches.length">
    <li *ngFor="let branch of branches; let serialNo = index" class="list-group-item">
      {{ serialNo+1 }}. {{ branch.BranchCode }} {{ branch.Description }}
    </li>
  </ul>
<ul>

根据我的理解,我认为可以尝试和更新

© www.soinside.com 2019 - 2024. All rights reserved.