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

前端 未结 3 862
一个人的身影
一个人的身影 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:35

    The new HttpClient in Angular 4.3 has currently 3 protoypes for get

    They are

    get(url: string, options: {
        headers?: HttpHeaders;
        observe: 'events';
        params?: HttpParams;
        reportProgress?: boolean;
        responseType?: 'json';
        withCredentials?: boolean;
    }): Observable>;
    
    get(url: string, options: {
        headers?: HttpHeaders;
        observe: 'response';
        params?: HttpParams;
        reportProgress?: boolean;
        responseType?: 'json';
        withCredentials?: boolean;
    }): Observable>;
    
    get(url: string, options?: {
        headers?: HttpHeaders;
        observe?: 'body';
        params?: HttpParams;
        reportProgress?: boolean;
        responseType?: 'json';
        withCredentials?: boolean;
    }): Observable;
    

    The Comments at the top of client.d.ts state this.

     * Each request method has multiple signatures, and the return type varies according to which
     * signature is called (mainly the values of `observe` and `responseType`).
    

    The really important part is the observe parameter

    get(url, {observe: 'events'}) returns HttpEvent

    get(url, {observe: 'response'}) returns HttpResponse

    get(url, {observe: 'body'}) returns T


    Note: if you subclass the options part into a method you must return a type of Object, without that the compiler will automatically select the first method which happens to return HttpEvent

    so

    getOptions(): any {
        return { observe: 'body' }
    };
    

    and

    getOptions(): any {
        return { observe: 'response' }
    };
    

    will compile to the wrong interface and return HttpEvent, but

    getOptions(): object {
        return { observe: 'body'}
    };
    

    and

    getOptions(): object {
        return { observe: 'response'}
    };
    

    will return T and HttpResponse respectively

提交回复
热议问题