[英]Can't bind from API data Angular 6
I'm working with API to get data and bind it to the HTML, i get to show the response on the console but once i try to bind data to the User screen i cannot, nothing is showing 我正在使用API来获取数据并将其绑定到HTML,但我会在控制台上显示响应,但是一旦尝试将数据绑定到“用户”屏幕,便无法显示任何内容
My HTML: 我的HTML:
<ul *ngFor="let item of items; let i of index">
<li class="fa fa-plus">{{item.name}} - {{i}}</li>
</ul>
My TS: 我的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;
}
}
)
} }
I'm trying to get data from an array of objects this is why i defined items as an object, if i tried to define it as an array, same result, cannot bind data to HTML 我试图从对象数组中获取数据,这就是为什么我将项目定义为对象的原因,如果我试图将其定义为数组,同样的结果,无法将数据绑定到HTML
My API Link: 我的API链接:
http://5a12745f748faa001280a746.mockapi.io/v1/stores/item http://5a12745f748faa001280a746.mockapi.io/v1/stores/item
Any questions or missing info tell me but kindly i need help binding this data 任何问题或信息丢失都会告诉我,但是请绑定数据需要帮助
Two things, HTML first : let i = index
is the syntax. 两件事,首先是HTML: let i = index
是语法。
The second one, you have a condition in your binding : 第二个,绑定中有一个条件:
if (res.Success) {
this.items = res;
}
This implies that your response has a Success
property. 这意味着您的响应具有Success
属性。
I checked your API link, and it doesn't. 我检查了您的API链接,但没有。
So in your service, either you use Http from @angular/http
or HttpClient from @angular/common/http
. 因此,在您的服务中,您可以使用Http from @angular/http
或HttpClient from @angular/common/http
。 Here are the two syntaxes : 这是两种语法:
// Http
return this.http.get('url').map(res => res.json());
// HttpClient
return this.http.get<any[]>('url');
For the condition, change to the following, to check if you have data. 对于条件,请更改为以下内容,以检查是否有数据。 You don't need to check for success because you have a special callback for that. 您不需要检查是否成功,因为您有一个特殊的回调。 This means you will always have succeed where the condition is. 这意味着您将始终在成功的条件下取得成功。
if (res) {
this.items = res;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.