[英]Why does Angular give me a length related error, when I can console log the length if I wanted to?
我確實相信這可能是我沒有給 Angular 最可能想要的正確類型,但在這種情況下它沒有意義。 終端上沒有錯誤,但控制台說:
正如我們所看到的,如果它顯然可以讀取 length 屬性(我在圖像中突出顯示了下面的那部分),那么為什么它說它不能?
import { Component, OnInit } from '@angular/core';
import { ClientService } from '../../services/client.service';
import { Client } from '../../models/Client';
@Component({
selector: 'app-clients',
templateUrl: './clients.component.html',
styleUrls: ['./clients.component.css']
})
export class ClientsComponent implements OnInit {
clients!: Client[];
totalOwed!: number;
constructor(private clientService: ClientService) { }
ngOnInit() {
this.clientService.getClients()
.subscribe(clients => {
/* console.log(clients), reveals all clients in Firestore
and we can also console.log the length here as 3 */
console.log(clients.length);
this.clients = clients;
this.getTotalOwed();
});
}
}
更新的問題詳細信息:是的,看起來我正在訪問模板 html 區域中的長度屬性。 怎么修?
<!-- clients-component-html -->
<div class="row">
<div class="col-md-6">
<h2><i class = "fa fa-users"></i>Clients</h2>
</div>
<div class="col-md-6">
<h5 class="text-right text-secondary">Total Owed: {{totalOwed | currency: "USD": "symbol"}} </h5>
</div>
</div>
<table *ngIf="clients.length > 0; else noClients" class="table table-striped">
<thead class="thead-inverse">
<tr>
<th>Name</th>
<th>Email</th>
<th>Balance</th>
<th> </th>
</tr>
</thead>
<tbody>
<tr *ngFor="let client of clients">
<td>{{ client.firstName }} {{ client.lastName }}</td>
<td>{{ client.email }}</td>
<td>{{ client.balance | currency: "USD": "symbol"}}</td>
<td>
<a
routerLink="client/{{ client.id }}" class="btn btn-secondary btn-sm">
<i class="fa fa-arrow-circle-o-right"></i>
Details
</a>
</td>
</tr>
</tbody>
</table>
<ng-template #noClients>
<hr>
<h5>There are no clients in the system</h5>
</ng-template>
您可能甚至在分配之前就訪問了模板中的variable.length
。
在模板中,使用ngIf
或variable?.length
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.