无法从 API 数据绑定 Angular 6



我正在使用 API 获取数据并将其绑定到 HTML,我可以在控制台上显示响应,但是一旦我尝试将数据绑定到用户屏幕,我就无法显示任何内容

我的网页:

<ul *ngFor="let item of items; let i of index">
<li class="fa fa-plus">{{item.name}} - {{i}}</li>
</ul>

我的 TS:

id: number;
name:string;
imageUrl: string;
items:any = {}; 
ngOnInit() {
this.getItems();
}
getItems() {
this.getItemsService.getItems().subscribe(
res => {
console.log(res)
if (res.Success) {
this.items = res;
}
}
)

}

我正在尝试从对象数组中获取数据这就是为什么我将项目定义为对象,如果我尝试将其定义为数组,相同的结果,无法将数据绑定到 HTML

我的API链接:

http://5a12745f748faa001280a746.mockapi.io/v1/stores/item

任何问题或缺少的信息告诉我,但请帮助绑定此数据

两件事,HTML 第一:let i = index是语法。

第二个,你的绑定中有一个条件:

if (res.Success) {
this.items = res;
}

这意味着您的响应具有Success属性。

我检查了您的 API 链接,但没有。

所以在你的服务中,要么你使用Http from @angular/http,要么使用HttpClient from @angular/common/http。以下是两种语法:

// Http
return this.http.get('url').map(res => res.json());
// HttpClient
return this.http.get<any[]>('url');

对于条件,请更改为以下内容,以检查您是否有数据。您不需要检查成功,因为您有一个特殊的回调。这意味着您将始终在条件所在的地方取得成功。

if (res) {
this.items = res;
}

最新更新