Angular httpClient returns property does not exist on object

时光怂恿深爱的人放手 提交于 2019-12-03 16:07:36

The docs state when using 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.

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;
 });
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!