如何使用 Angular 访问 JSON 中的特定对象?

How to access specific object in JSON using Angular?

我正在尝试从 API 访问某些数据,但遇到了问题。这是 API 中 JSON 的结构:

我想在 value 中访问 NameStateNameCityName 以循环访问 table。我收到明显的错误“无法找到 'object' 类型的不同支持对象 '[object Object]'。NgFor 仅支持绑定到 Iterables,例如 Arrays”,因为 ngFor 不遍历数组。如何修复我的代码以遍历数据以填充我的 table?

component.ts:

@Component({
  selector: 'app-search',
  templateUrl: './search.component.html',
  styleUrls: ['./search.component.css']
})
export class SearchComponent implements OnInit {

  customer: any;

 constructor(private Service: CustomerDataService) { }

  ngOnInit(): void {
    this.getCustomerData();
  }

  public getCustomerData() {
    this.Service.getCustomers().subscribe((data)=>{
      console.log(data);
      this.customer = data;
    }) 
  }

}

HTML:

<div class="container">
    <form class="form-inline">
        <div class="input-group mb-2">
            <div class="has-clear">
                <input type="text" name="search" required class="form-control" placeholder="Name" />
                <button class="clear-data" type="reset"><i class="icon-close-bold-sm"></i></button>
            </div>
            <button type="submit" class="btn btn-primary mb-2 ml-3">Search</button>
        </div>
    </form>
    <div class="table-responsive">
        <table class="table table-striped">
            <thead>
                <tr>
                    <th scope="col">Name</th>
                    <th scope="col">City</th>
                    <th scope="col">State</th>
                </tr>
            </thead>
            <tbody>
                <tr *ngFor = "let customers of customer">
                    <td scope="row">{{customers.value.Name}}</td>
                    <td scope="row">{{customers.value.StateName}}</td>
                    <td scope="row">{{customers.value.CityName}}</td>
                </tr>
            </tbody>
        </table>
    </div>
</div>

该值是一个数组而不是对象,所以

  public getCustomerData() {
    this.Service.getCustomers().subscribe((data)=>{
      console.log(data);
      this.customer = data.value;
    }) 
  }

并在您的模板中

<tr *ngFor = "let customers of customer">
    <td scope="row">{{customers.Name}}</td>
    <td scope="row">{{customers.StateName}}</td>
    <td scope="row">{{customers.CityName}}</td>
</tr>

或者您可以只编辑您的模板

<tr *ngFor = "let customers of customer.value">
    <td scope="row">{{customers.Name}}</td>
    <td scope="row">{{customers.StateName}}</td>
    <td scope="row">{{customers.CityName}}</td>
</tr>

考虑使用 | async 直接在你的 html

中访问 observable
<tr *ngFor = "let customer of customers$ | async">
    <td scope="row">{{customer.Name}}</td>
    <td scope="row">{{customer.StateName}}</td>
    <td scope="row">{{customer.CityName}}</td>
</tr>

并在您的组件中

customers$ : Observable<Customer> = this.getCustomerData();

您可以使用地图运算符将 getCustomerData 更新为 return 您在 value 属性 中的客户列表。