0

I'm trying to get the X-Total-Count value from a get request.

In my meal.service.ts I use this function to call the service.

import { Injectable }              from '@angular/core';
import { Observable }              from 'rxjs/Observable';
import { catchError, map, tap }    from 'rxjs/operators';
import { of }                      from 'rxjs/observable/of';
import { HttpClient, HttpHeaders,
         HttpParams,
         HttpResponse }            from '@angular/common/http';

getMeals (page:number): Observable<Meal[]> {
    let httpParams = new HttpParams().set('where', '%')
      .set('orderBy', 'meal_name')
      .set('page', page.toString())
      .set('items', '10');
    return this.http.get<Meal[]>(this.mealUrl, { params: httpParams  })
      .pipe(
        tap(meals => { this.log(`fetched entries`); console.log(meals.headers)  }),
// meals.headers is undefined
        catchError(this.handleError<Meal[]>('getMeals'))
      );
  };

I get the error:

ERROR in src/app/meal.service.ts(52,71): error TS2339: Property 'headers' does not exist on type 'Meal[]'.

In this.meals I see only the datasets from typ Meal but no headers.

In my meals.component.ts I'm using this service:

  getMeals(page:number): void {
    this.mealService.getMeals(this.page)
      .subscribe(data => {
        this.count = data.headers.get('X-Total-Count'), // didn't work
        this.meals = data
      })
  }

What's the right method to get the headers from request?

I changed my code to:

  getMeals (page:number): Observable<any> {
    let httpParams = new HttpParams().set('where', '%')
      .set('orderBy', 'meal_name')
      .set('page', page.toString())
      .set('items', '10');
    return this.http.get<any>(this.mealUrl, { params: httpParams, observe: 'response'} )
      .pipe(
        catchError(this.handleError<any>('getMeals'))
      );
  };

After that I have a body and headers.

Jota.Toledo
  • 27,293
  • 11
  • 59
  • 73
Sven
  • 87
  • 1
  • 10

1 Answers1

2

I had to change the Observable to Observaable and add the observe: 'response'.

  getMeals (page:number): Observable<any> {
    let httpParams = new HttpParams().set('where', '%')
      .set('orderBy', 'meal_name')
      .set('page', page.toString())
      .set('items', '10');
    //this.messageService.add('Debug: ' + httpParams);
    return this.http.get(this.mealUrl, { params: httpParams, observe: 'response'} )
      .pipe(
        //tap(meals => { console.log(meals.headers)  }),
        catchError(this.handleError<any>('getMeals'))
      );
  };

Thanks for the link to the documentation.

Sven
  • 87
  • 1
  • 10