【问题标题】:Can't bind from API data Angular 6无法从API数据Angular 6绑定
【发布时间】:2018-06-25 07:22:55
【问题描述】:

我正在使用 API 来获取数据并将其绑定到 HTML,我可以在控制台上显示响应,但是一旦我尝试将数据绑定到用户屏幕我就不能,什么都没有显示

我的 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

如有任何问题或缺少的信息,请告诉我,但我需要帮助绑定这些数据

【问题讨论】:

  • 项目:任何 = [];改成这个
  • 这不会纠正他的问题。
  • 并且让 i = index 也适用于 index
  • 尝试使用{{items | json}} 只是为了检查模板中是否有值,另外请发布您的console.log 返回什么
  • 问题已解决,感谢您的帮助^_^

标签: javascript arrays angular typescript get


【解决方案1】:

两件事,HTML 优先:let i = index 是语法。

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

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

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

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

因此,在您的服务中,您可以使用Http from @angular/httpHttpClient 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;
}

【讨论】:

  • HttpClient 来自 Angular 表单? ,我是从 angular common 导入的
猜你喜欢
  • 2019-06-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多