Search code examples
c#angulartypescripthttpangular-httpclient

HttpClient does not work as opposed to Http for backend queries with Angular


Ok, I'll explain my problem. I'm starting on Angular and this is the first time I'm doing a REST API, so something can escape me.

In my case, I use a Period object in Typescript and in C#, here they are:

Period TS:

export class Period {
    id: number;
    year: string;
    month: string;
    blocked: boolean;

    constructor(id: number, year: string, month: string, blocked: boolean) {
        this.id = id;
        this.year = year;
        this.month = month;
        this.blocked = blocked;
    }
}

Period C#:

public class Period
  {
    [JsonProperty(PropertyName = "id")]
    public int ID { get; set; }
    [JsonProperty(PropertyName = "year")]
    public string Year { get; set; }
    [JsonProperty(PropertyName = "month")]
    public string Month { get; set; }
    [JsonProperty(PropertyName = "blocked")]
    public bool Blocked { get; set; }

    public Period() { }
  }

Until then, I managed to recover data from my database via Postman.

Postman: GET -> https://localhost:5001/api/period/GetAllPeriods

[
  {
     "id": 122,
     "year": "2019",
     "month": "03",
     "blocked": false
  },
  {
     "id": 121,
     "year": "2019",
     "month": "02",
     "blocked": false
  }, ...
]

enter image description here

I did some research and several tests, and the code below works. I retrieve my JSON data that I transform into a Period object list into Typescript. Then, I display them on my page and everything works correctly.

But on the Angular documentation, it is written that Http is obsolete and that it is better to use HttpClient.

period.service.ts: Http

export class PeriodService {

  constructor(private http: Http) { }

  //Http
  getPeriods(): Observable<Period[]> {
    return this.http.get('/api/period/GetAllPeriods')
      .pipe(
        catchError(this.handleError),
        map(response => {
          const periods = response.json();
          return periods.map((period) => new Period(period.id, period.year, period.month, period.blocked));
        })
      );
  }

  private handleError(error: HttpErrorResponse) {
    if (error.error instanceof ErrorEvent) {
      // A client-side or network error occurred. Handle it accordingly.
      console.error('An error occurred:', error.error.message);
    } else {
      // The backend returned an unsuccessful response code.
      // The response body may contain clues as to what went wrong,
      console.error(
        `Backend returned code ${error.status}, ` +
        `body was: ${error.error}`);
      console.error(error);
    }
    // return an observable with a user-facing error message
    return throwError(
      'Something bad happened; please try again later.');
  };
}

So I tried to use HttpClient. However, I can not recover the data at my service.

period.service.ts: HttpClient

export class PeriodService {

  constructor(private http: HttpClient) { }

  //HttpClient
  getPeriods(): Observable<Period[]> {
    return this.http.get<Period[]>('https://localhost:5001/api/period/GetAllPeriods')
      .pipe(
        catchError(this.handleError)
      );
  }

  private handleError(error: HttpErrorResponse) {
    if (error.error instanceof ErrorEvent) {
      // A client-side or network error occurred. Handle it accordingly.
      console.error('An error occurred:', error.error.message);
    } else {
      // The backend returned an unsuccessful response code.
      // The response body may contain clues as to what went wrong,
      console.error(
        `Backend returned code ${error.status}, ` +
        `body was: ${error.error}`);
      console.error(error);
    }
    // return an observable with a user-facing error message
    return throwError(
      'Something bad happened; please try again later.');
  };
}

enter image description here

To be clearer, I get the JSON data from the API, but when I use the HttpClient service, an error message appears in the browser console because it can not find the data yet accessible. So, I think my problem comes from service with HttpClient.

If you have ideas I am interested. Thank you in advance.


Solution

  • Well it's been several days that I am stuck on this problem, and once my question asked, I just found the solution ...

    My problem was: import {HttpClientInMemoryWebApiModule} from 'angular-in-memory-web-api';

    It turns out that to develop my application I started using HttpClientInMemoryWebApiModule. But this module is incompatible with HttpClient. It must be removed to use HttpClient.

    Now my application is working properly and displays the data.