首页 > 解决方案 > 从角度“导致未定义”调用 API

问题描述

我正在努力弄清楚我的代码有什么问题。我正在尝试从我的角度代码中调用休息 API,但它导致“TypeError:无法读取未定义的属性 'id'”

我的clients.ervice.ts代码如下所示:

import { Injectable } from '@angular/core';
import { Clients } from './clients.model';
import { HttpClient, HttpErrorResponse } from '@angular/common/http';
import { Observable} from 'rxjs';
@Injectable({
  providedIn: 'root'
})
export class ClientsService {

  clientsUrl="http://localhost:21063/api/clints

  constructor(private http:HttpClient) { }
getAllClients():Observable<Clients[]>{
    return this.http.get<Clients[]>(this.clientsUrl);

}

我在client.component.ts中的代码

 constructor(private formBuilder: FormBuilder, private Service: ClientsService) { }
  clients:Clients[];
  ngOnInit() {

this.Service.getAllClients()
      .subscribe(data => this.clients=data);

这是model.ts

export class Clients {
    id:number;
    name:string;
    phone:string;
    address:string;
    type:string;
    account:number;
    nots:string;
    branchId:number;
}

最后我的模板:

                  <tbody>
                        <tr *ngFor="let item of clients"></tr>
                        <td>{{item.id}} </td>
                        <td>{{item.name}} </td>
                        <td>{{item.phone}} </td>
                        <td>{{item.address}} </td>
                        <td>{{item.account}} </td>
                        <td>{{item.nots}} </td>

                    </tbody>

提前感谢您为解决和理解此问题提供的任何帮助

标签: angulartypescript

解决方案


没问题,你自己放轻松,你忘了让 tr 元素包裹所有 td 元素

<tbody>
  <tr *ngFor="let item of clients">
      <td>{{item.id}} </td>
      <td>{{item.name}} </td>
      <td>{{item.phone}} </td>
      <td>{{item.address}} </td>
      <td>{{item.account}} </td>
      <td>{{item.nots}} </td>
  </tr>
</tbody>

推荐阅读