Angular httpClient returns property does not exist on object
Asked Answered
F

1

7
  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?

Frecklefaced answered 2/11, 2017 at 12:20 Comment(1)
can you add the value printed by console.log(data)?Scrivings
P
5

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;
 });
Possessive answered 4/11, 2017 at 10:33 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.