1

I want to format my API response through a callback function and get the data inside the angular subscribe

I have used mergemap but it was no use

this.http.get('https://some.com/questions.xml', {headers, responseType: 'text'})
  .mergeMap(
    res => xml2js.parseString(
      res,
      { explicitArray: false },
      (error, result) => {
        if (error) {
          throw new Error(error);
        } else {
          console.log(result);
          return result;
        }
      }
    )
  ).subscribe(
    data => { console.log("response", data); },
    error => { console.log(error); }
  );

I wanted to get the response JSON in subscribe but I am getting TypeError: You provided an invalid object where a stream was expected. You can provide an Observable, Promise, Array, or Iterable.

Denis Zavedeev
  • 7,627
  • 4
  • 32
  • 53

2 Answers2

0

MergeMap expects, stream as data. You re returning value and throwing error. You have to return a promise from there.

// RxJS v6+
import { fromEvent } from 'rxjs';
import { ajax } from 'rxjs/ajax';
import { mergeMap } from 'rxjs/operators';

// free api url
const API_URL = 'https://jsonplaceholder.typicode.com/todos/1';

// streams
const click$ = fromEvent(document, 'click');

click$
  .pipe(
    /*
     * Using mergeMap for example, but generally for GET requests
     * you will prefer switchMap.
     * Also, if you do not need the parameter like
     * below you could use mergeMapTo instead.
     * ex. mergeMapTo(ajax.getJSON(API_URL))
     */
    mergeMap(() => ajax.getJSON(API_URL))
  )
  // { userId: 1, id: 1, ...}
  .subscribe(console.log);

More info. Please check RXJS docs. https://www.learnrxjs.io/operators/transformation/mergemap.html

xdeepakv
  • 7,835
  • 2
  • 22
  • 32
0

Like xdeepakv mentioned, when using mergeMap or switchMap ...etc, you should return a promise or an observable. While xml2js.parseString(...) is of type SAXParser. Therefore you should be using a map.

Or you can check this stackoverflow question on how you can transform parseString(...) into a promise.

Boudi
  • 122
  • 1
  • 7