Angular HttpClient return expecting observable<HttpEvent<any> rather than observable<any>

天涯浪子 提交于 2019-11-28 23:28:33

It's strange, don't give error if you write

GetPortfolio(portfolioId: string): Observable<Portfolio> {
    return this.http.get<Portfolio>('....', {
        headers: new HttpHeaders(
            {
                'Content-Type': 'application/json',
            })   
    });
}

It's look like, the compiler expect an object with the properites headers,params,observe..., but as your object have no type, the compiler can accept it

even you can do

headers: HttpHeaders = new HttpHeaders({
        'Content-Type': 'application/json',
    })
GetPortfolio(portfolioId: string): Observable<Portfolio> {
        return this.http.get<Portfolio>('...', {
            headers: this.headers
        })
    }

Typecast your httpOptions

private httpOptions: {
    headers: HttpHeaders
};

The typescript compiler is pulling the wrong get method type (src)

/**
* 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<T>(url: string, options: {
    headers?: HttpHeaders | {[header: string]: string | string[]},
    observe: 'events',
    params?: HttpParams|{[param: string]: string | string[]},
    reportProgress?: boolean,
    responseType?: 'json',
    withCredentials?: boolean,
}): Observable<HttpEvent<T>>;

When you specify the type with headers, it pulls the correct type. (src)

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

i solve this casting my header params like this

return this.http.get<SomeModel>(someUrl, <Object>this.options);

As this is a service 'PortfolioService' we may not need interface here, instead we can use of type any, and also GET method is only necessary here.

GetPortfolio(portfolioId): Observable<any> {
  return this.http.get(this.apiUrl + '/${portfolioId}')
         .map((response:any) => {
              return response;
         });
}

This should work, please try.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!