Angular 4 proper way to cast http response

后端 未结 3 1171
自闭症患者
自闭症患者 2021-01-17 05:03

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         


        
3条回答
  •  悲&欢浪女
    2021-01-17 05:46

    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.

提交回复
热议问题