Property 'data' does not exist on type 'HttpEvent'

前端 未结 3 856
一个人的身影
一个人的身影 2020-12-21 00:35

I have a setup like this

  • api.service (wraps the httpClient Module)
  • customer.service

the api service get looks like this:



        
3条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-21 01:25

    Looking at the angular source code (v4.3.3), when you wrap the http.get without specifying the type of options the typescript compiler is using this type definition

    /**
     * Construct a GET request which interprets the body as JSON and returns the full event stream.
     *
     * @return an `Observable` of all `HttpEvent`s for the request, with a body type of `T`.
     */
    get(url: string, options: {
        headers?: HttpHeaders;
        observe: 'events';
        params?: HttpParams;
        reportProgress?: boolean;
        responseType?: 'json';
        withCredentials?: boolean;
    }): Observable>;
    

    To get the typescript compiler to use the correct type definition, you can specify that the options is of type Object. In your case the getOptions method should specify it is returning the type Object.

    get(url: string, options?) {
        return this.httpClient.get(
            this.apiUrl + url, 
            this.getOptions(options) // this.getOptions needs to specify it is returning the type Object
        );
    }
    
    getOptions(options): Object {...}
    

    Now the typescript compiler will find the correct type definition

    /**
     * Construct a GET request which interprets the body as JSON and returns it.
     *
     * @return an `Observable` of the body as type `T`.
     */
    get(url: string, options?: {
        headers?: HttpHeaders;
        observe?: 'body';
        params?: HttpParams;
        reportProgress?: boolean;
        responseType?: 'json';
        withCredentials?: boolean;
    }): Observable;
    

    and finally now you can access data

    const customer = res.data;
    

提交回复
热议问题