Search code examples
angularangular-httpclient

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


I'm getting a compilation error on the return type when using HttpClient. In my function GetPortfolio, I'm expecting the GET call to return the json object of type Observable<Portfolio> but it's giving the error:

Type Observable<HttpEvent<Portfolio>> is not assignable to type Observable<Portfolio>. Type HttpEvent<Portfolio> is not assignable to type Portfolio. Type HttpProgressEvent is not assignable to type Portfolio. Property name is missing in type HttpProgressEvent.

My code:

import { Injectable } from '@angular/core';
import { environment } from './environments/environment';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Observable } from 'rxjs/Observable';


export interface Portfolio {
  name: string;
  id: string;
}

@Injectable()
export class PortfolioService {

    private httpOptions;

    apiUrl: string;

    constructor(private http: HttpClient) {
      this.apiUrl = environment.apiUrl + "/api/portfolios";

      this.httpOptions = {
        headers: new HttpHeaders(
          {
            'Content-Type': 'application/json',
          })   
      };
    }


    GetPortfolio(portfolioId: string): Observable<Portfolio> {
      return this.http.get<Portfolio>(this.apiUrl + '/${portfolioId}', this.httpOptions);
   }

}

From the angular hero tutorial and docs HttpClient requests should expect Observable<any>: Angular HttpClient doc

So am I doing something wrong? Or should I be setting the return value to Observable<HttpEvent<Portfolio>> ?


Solution

  • 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
            })
        }