I\'ve created a service in Angular 4 and I\'m fetching data via REST/JSON (new to Angular) using this code:
Interface
export interface IItem {
Id
The specific type for the get should describe the shape of the actual response JSON you expect to receive. Then the compiler can actually help you by telling you whether you’re accessing and returning the right things. In your case:
getItems(): Observable {
return this._http.get<{ d: { results: IItem[] } }>('url')
.map(response => response.d.results)
.do(data => {
console.log(data);
}):
}
Note that none of this is casting the response data, just describing it.
As for your other suggestion:
.get(...)
.map((data) => data['d']['results'])
If you’re going to assert the type of the response wrongly then make unsafe property accesses with a result the compiler can only assume is any
, you might as well not be using types at all. Don’t just ignore the compiler when it tells you you’re accessing the wrong properties.