简体   繁体   中英

Why does Angular give me a length related error, when I can console log the length if I wanted to?

I do believe this might be me not giving Angular the right type of what it wants most likely, but it doesn't make sense in this scenario. There's no errors on the terminal, but the console says:

在此处输入图片说明

and as we can see, if it can read the length property obviously (I highlighted that part below in the image), then, why does it say that it can't?

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

Updated Question Details : Yes, it does look like I'm accessing the length property here in the template html area. How to fix?

<!-- 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>

You are probably accessing the variable.length in the template even before it has been assigned.

In the template, either use an ngIf or variable?.length .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM