【问题标题】:ngFor over object instead of array?ngFor 在对象而不是数组上?
【发布时间】:2018-12-22 15:11:29
【问题描述】:

在控制台中收到此错误:

找不到不同类型的支持对象“[object Object]” '目的'。 NgFor 只支持绑定到 Arrays 等 Iterables。

services.ts

      private url = "https://api.iextrading.com/1.0/stock/market/batch?symbols=SNAP,fb,AIG%2b,GOOG,AAPL,AMZN&types=quote";

      constructor(private http: HttpClient) {}

      getCID(): Observable<any> {
        return this.http.get<any>(this.url);
      }

组件.ts

      ngOnInit() {
        this.svc.getCID().subscribe(data => {
          this.cidData = data;
          console.log(data);
        });

component.html

    <div *ngIf="cidData">
      <ul>
        <li *ngFor="let x of cidData">
          <a routerLink="/companydetails/{{x.symbol}}">{{x.symbol}}</a>

API 调用提供

    {"GOOG":{"quote":{"symbol":"GOOG","companyName":"Alphabet Inc."}}, "SNAP":{etc...}

我认为问题在于 cidData 不是数组,但我不确定如何将其作为数组返回

【问题讨论】:

    标签: javascript angular api


    【解决方案1】:

    如果您使用的是 Angular 版本 6,那么您可以使用内置的管道键值来遍历对象

     <li *ngFor="let x of cidData | keyvalue">
          <a routerLink="/companydetails/{{x.value.quote.symbol}}">{{x.value.quote.symbol}}</a>
    

    【讨论】:

      【解决方案2】:

      通过Object.values(obj)把你的对象变成一个数组,可以看here

      // object with your example here
          ngOnInit() {
              this.svc.getCID().subscribe(data => {
                  this.cidData = data;
                  let array = 
                  Object.values(this.cidData.GOOD) 
                  // here you have an array    
                  console.log(array);
         });

      【讨论】:

      • 一般只有一个对象,否则如果有更多对象则必须是一个表响应
      猜你喜欢
      • 2017-11-02
      • 2018-07-31
      • 2019-02-19
      • 2022-07-07
      • 2019-07-23
      • 1970-01-01
      • 1970-01-01
      • 2021-08-15
      • 2019-04-22
      相关资源
      最近更新 更多