角度:“找不到类型为'object'的其他支持对象'[object Object]'。NgFor仅支持绑定到Iterables,例如数组。”

时间:2020-01-24 03:09:02

标签: angular

我无法弄清楚为什么会出现此Angular错误:”“找不到类型为'object'的其他支持对象'[object Object]'。NgFor仅支持绑定到可迭代对象,例如数组。”

我的猜测是,由于某种原因,我的服务返回的observable正在返回一个对象,当我需要将其作为数组时-我只是不知道它是如何工作的。任何帮助将非常感激!我还看到其他人问过有关同一错误的其他问题,但是我所看到的所有解决方案都不对我有用。

app.component:

export class AppComponent implements OnInit {
  constructor(private playersService: PlayersService) { }

  teams: string[];
  year: number = 2019; 
  selectedYear: number;
  years: number[] = this.getYears(1900);

  ngOnInit() {
    this.refreshTeams(this.year);
  }

  refreshTeams(year: number) {
    this.teams = this.playersService.fetchTeams(this.year).subscribe(data => { this.teams = data });
  }

  onYearChange() : void {
    this.year = this.selectedYear;
    this.refreshTeams(this.year);
  }

  getYears(startYear) : number[] {
    var currentYear = new Date().getFullYear()
    var years = [];
    for (var x = currentYear; x >= startYear; x--) {
      years.push(x);
    }
    return years;
  }
}

players.service:

export class PlayersService {

    constructor(private http: HttpClient) { }

    returnedTeams = [];

    fetchTeams(year: number) : any {

        var queryString = `http://lookup-service-prod.mlb.com/json/named.team_all_season.bam?sport_code='mlb'&all_star_sw='N'&sort_order=name_asc&season='${year}'`;

        return this.http.get(queryString)
            .pipe(
                map(data => {
                    const teamArray = [];
                    var rows = data['team_all_season'].queryResults.row;
                    for (var item in rows) {
                        teamArray.push(rows[item].name_display_full);
                    }
                    return teamArray;
                })
            )
    }
}

app.component.html:

<button (click)="fetchTeams()">Fetch</button>

<select [(ngModel)]="selectedYear" (change)="onYearChange($event)">
  <option *ngFor = "let year of years" value="{{ year }}">{{ year }}</option>
</select>

<select>
  <option *ngFor="let team of teams">
    {{ team }}
  </option>
</select>

2 个答案:

答案 0 :(得分:1)

问题是您将subscribe调用的结果分配给teams属性:

this.teams = this.playersService.fetchTeams(this.year).subscribe(...);

由于该调用返回了Subscription,因此它与ngFor不兼容。错误可能在Observable发出其值之前发生。为避免这种情况,您应该仅在回调内部设置teams属性:

this.playersService.fetchTeams(this.year).subscribe(data => {
  this.teams = data;
});

答案 1 :(得分:1)

您可以使用Angular async管道,而不必手动订阅。

async还会自动取消订阅可观察对象。

<select>
  <option *ngFor="let team of (teams$ | async)">
    {{ team }}
  </option>
</select>

comp.ts

teams$: Observable<string[]>;
refreshTeams(year: number) {
    this.teams$ = this.playersService.fetchTeams(this.year);
}

Demo