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



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

我尝试应用 *ngIf 条件,以便仅在数据已经在 ngOnInit 父 ul tag 中订阅后使列表可见,如其他帖子之一所建议的那样。

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)

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

最初设置分支 = 空;

而不是在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>

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

最新更新