简体   繁体   English

处理来自Angular 5 Http调用的响应

[英]Handling the response from Angular 5 Http call

getItems() {
    this.fetchItemsService.fetchItems(this.url, this.searchTex).subscribe((res) => {
        this.repos = res['items'];
    })
}

Above code is working fine but initially I tried as follow 上面的代码工作正常,但最初我尝试如下

getItems() {
    this.fetchItemsService.fetchItems(this.url, this.searchText).subscribe((res) => {
       this.items= res.items;
   })
}

This is throwing an error Items is not defined on res 这将引发错误未在res上定义项目

res is an object res是一个对象

Why is it like that? 为什么会这样呢?

You can refer this link to know, why you can't use res.data instead of res['data'] . 您可以引用此链接来了解为什么不能使用res.data而不是res['data']

You can't write res.data because TypeScript correctly complains that the res object from the service does not have a data property. 您无法编写res.data因为TypeScript正确地抱怨服务中的res对象没有data属性。

The HttpClient.get() method parsed the JSON server response into the anonymous Object type. HttpClient.get()方法将JSON服务器响应解析为匿名Object类型。 It doesn't know what the shape of that object is. 它不知道该对象的形状是什么。

You can tell HttpClient the type of the response to make consuming the output easier and more obvious. 您可以告诉HttpClient响应的类型,以使使用输出变得更加轻松和明显。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM