Http to HttpClient

I’m trying to upgrade from Http to HttpClient and I’m running into issues with the XML response, it appears to be trying to parse it as JSON.

Any advice on how to get this working?

Here’s the code in my Provider:
import { HttpClient } from ‘@angular/common/http’;
import { Injectable } from ‘@angular/core’;
import { Http } from ‘@angular/http’;
import { NavParams } from ‘ionic-angular’;
import xml2js from ‘xml2js’;
import {Observable} from ‘rxjs/Rx’;
import { switchMap } from ‘rxjs/operators’;
import { HttpHeaders } from ‘@angular/common/http’;
import {tap} from ‘rxjs/operators’;

@Injectable()
export class SearchProvider {

search_value;

constructor(public navParams: NavParams, private http: Http) {
this.search_value = navParams.get(‘search_value’);
console.log(this.search_value);
}

getEmployees(): Observable<Employee[]> {
const url = ‘https://hardermech.quickbase.com/db/bm8j4cdjn?a=API_DoQuery&usertoken=bz98ti_bdcn_d799aghcb4vzt8c6xdqbwuxudje&query={24.SW.’ + this.search_value + ‘}&clist=10.37’;
const apiData = {};
const httpOptions = {
headers: new HttpHeaders({
responseType: ‘text’
})
};
// Call to Quickbase API for data
return this.http.post(url, httpOptions).map( res => {
let data;
xml2js.parseString( res.text(), function (err, result) {
data = result
});
return data;
})
}

Chrome Console:
core.js:1449 ERROR

  1. HttpErrorResponse

  2. error:

  3. error: SyntaxError: Unexpected token < in JSON at position 0 at JSON.parse (<anonymous>) at XMLHttpRequest.onLoad

This doesn’t say “HttpClient”. Additionally, you’ve omitted apiData from the post call, making your options be considered the post payload.

1 Like

So if you read HttpClient documentation you will see that it is a feature that default expected response is json response. To work around it you need to set responseType (which you try to do but I am not sure you form request correctly). See more here: https://angular.io/guide/http#requesting-non-json-data

Maybe try to do it this way:

  getEmployees(): Observable<Employee[]> {
    const url = ‘https://hardermech.quickbase.com/db/bm8j4cdjn?a=API_DoQuery&usertoken=bz98ti_bdcn_d799aghcb4vzt8c6xdqbwuxudje&query={24.SW.’ + this.search_value + ‘}&clist=10.37’;
      const apiData = {};
    // Call to Quickbase API for data
    return this.http.post(url, { responseType: ‘text’ }).subscribe(res => {
      let data;
      xml2js.parseString(res.text(), function (err, result) {
        data = result
      });
      return data;
    })
  }