[英]Handling the response from Angular 5 Http call
getItems() {
this.fetchItemsService.fetchItems(this.url, this.searchTex).subscribe((res) => {
this.repos = res['items'];
})
}
上面的代码工作正常,但最初我尝试如下
getItems() {
this.fetchItemsService.fetchItems(this.url, this.searchText).subscribe((res) => {
this.items= res.items;
})
}
这将引发错误未在res上定义项目
res是一个对象
为什么会这样呢?
您可以引用此链接来了解为什么不能使用res.data
而不是res['data']
。
您无法编写res.data
因为TypeScript正确地抱怨服务中的res
对象没有data
属性。
HttpClient.get()
方法将JSON服务器响应解析为匿名Object类型。 它不知道该对象的形状是什么。
您可以告诉HttpClient
响应的类型,以使使用输出变得更加轻松和明显。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.