【发布时间】:2019-05-09 09:23:57
【问题描述】:
我一直在尝试进行 API 调用,但没有成功。显示名称时收到此错误消息。非常抱歉,我已经粘贴了三个文件,但这是我在这里的第一个问题,我是新手。感谢您的帮助。
Cannot find a differ supporting object '[object Object]' of type 'object'. NgFor only supports binding to Iterables such as Arrays.
这是我的beers.service.ts 文件
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
@Injectable({
providedIn: 'root'
})
export class BeersService {
private beerUrl = 'https://api.punkapi.com/v2/beers/';
beers;
constructor(private _httpClient: HttpClient) { }
getListOfBeer() {
return this._httpClient.get(this.beerUrl).subscribe(
res => {
this.beers = res;
});
}
}
这是我的app.component.ts 我感觉问题出在构造函数上,但我尝试的一切都没有成功。
import { Component } from '@angular/core';
import { BeersService } from './beers.service';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.scss']
})
export class AppComponent {
beers;
constructor(private _beerService: BeersService) {
this.beers = _beerService.getListOfBeer()
}
}
最后是我的app.component.html
<div class="container">
<div *ngFor="let beer of beers">
<p>{{ beer.name }}</p>
</div>
</div>
【问题讨论】:
-
beers可能是一个对象,如果您想在 HTML 中对其进行迭代,则需要将其设为Array -
我理解这一点,并尝试将啤酒导出为
beers = Beers[];或beers = any;,甚至将get 请求作为可观察的但没有运气。 @xyz -
你能做一个啤酒的控制台日志并更新你在日志中看到的问题吗?
标签: angular typescript api constructor ngfor