在<li>上应用* ngFor仅显示具有空数据的列表,而在ngOnInit()上从api提取数据时呢?

时间:2019-04-20 06:32:05

标签: angular7 ngfor

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

我尝试应用* ngIf条件,以便仅在其他帖子之一中建议的li的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)

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

1 个答案:

答案 0 :(得分:0)

最初设置的分支= 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>

据我了解,我认为可以尝试更新