Angular httpClient返回属性在对象上不存在 [英] Angular httpClient returns property does not exist on object

查看:262
本文介绍了Angular httpClient返回属性在对象上不存在的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  constructor(private http: HttpClient) {
  }
  ngOnInit() {
   this.http.get('url').subscribe(data => {
     console.log(data);
     console.log(data.login);
   });
  }
}

在这里,我可以在控制台中看到登录数据但我收到一条错误消息,指出数据上不存在属性登录。有没有使用界面的解决方法吗?因为我想要获取的数据非常庞大,并且将来可能会被修改,所以还有更好的方法吗?

Here, I can see the data with login in console but I get an error saying property login does not exist on data. Is there a workaround for this without using an interface? Because the data I want to get is pretty huge and will probably be modified in the future, so is there any better way?

推荐答案

HttpClient ...


 this.http.get('/api/items').subscribe(data => {
   // Read the result field from the JSON response.
   this.results = data['results'];
 });

在上面的示例中, data ['results]] 字段访问很突出,因为您使用括号表示法来访问结果字段。如果您尝试编写 data.results ,TypeScript会正确地抱怨从HTTP返回的对象没有结果属性。这是因为 HttpClient 将JSON响应解析为对象时,它不知道该对象的形状。

In the above example, the data['results'] field access stands out because you use bracket notation to access the results field. If you tried to write data.results, TypeScript would correctly complain that the Object coming back from HTTP does not have a results property. That's because while HttpClient parsed the JSON response into an Object, it doesn't know what shape that object is.

因此,您的选择是键入您的回复(文档和我都建议),然后使用方括号表示法。

So your options are to either type your response (which both docs and I would suggest), or then use the bracket notation.

输入响应将是创建一个接口/类,您将告诉它它是您期望的:

Typing the response would be to create an interface/class, which you tell that it is what you expect from the request:

export interface MyResponse {
  results: // your type here
}

this.http.get<MyResponse>('/api/items').subscribe(data => {
   this.results = data.results;
 });

这篇关于Angular httpClient返回属性在对象上不存在的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆