我无法弄清楚为什么会出现此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>
答案 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)