Angular httpClient返回对象上不存在的属性

标签 angular angular4-httpclient

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

在这里,我可以在控制台中看到带有登录名的数据,但我收到一条错误消息,指出数据上不存在属性登录名。有没有不使用接口(interface)的解决方法?因为我要获取的数据量比较大,以后可能还会修改,请问有什么更好的办法吗?

最佳答案

docs 使用 HttpClient 时的状态...

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

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.

因此您的选择是输入您的回复(我和文档都建议这样做),或者然后使用括号表示法。

键入响应将创建一个接口(interface)/类,您告诉它这是您对请求的期望:

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

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

关于Angular httpClient返回对象上不存在的属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47075175/

相关文章:

带有正文的 Angular HttpClient Get 方法

angular - 在订阅中访问时请求的响应不相同

angular - 为什么 Angular 教程不需要导入 Observable

angular - 如何通过 Angular 5 中的 `httpclient` 删除请求传递正文

php - Angular 4 使用 PHP POST 到 MYSQL 数据库

javascript - Angular 2 动态表单 - 实现取消功能

javascript - Ng Bootstrap 轮播全屏

angular - multi :true mean in providers in angular4 是什么意思

javascript - 在单击之前显示 mdTooltip,再次单击时隐藏

angular - 在 Angular 的 onInit() 内部编写订阅单元测试