Guide on formatting the API response using a callback function in Angular development

How can I reformat my API response using a callback function and access the data within the angular subscribe method?

I attempted to use mergemap but it didn't work as expected.

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

My intention was to receive the response JSON in the subscribe method, however, I am encountering an error message that states: TypeError: You provided an invalid object where a stream was expected. You can provide an Observable, Promise, Array, or Iterable.

Answer №1

As xdeepakv pointed out, it's important to remember that when utilizing functions like mergeMap or switchMap ...etc, you need to ensure that you return a promise or an observable. In the case of xml2js.parseString(...), which is of type SAXParser, using a map is more appropriate.

If you're unsure how to convert parseString(...) into a promise, check out this helpful stackoverflow thread for guidance.

Answer №2

Make sure MergeMap is expecting a stream as data, not just a value being returned with an error thrown. It's important to return a promise instead.

// Version 6 of RxJS
import { fromEvent } from 'rxjs';
import { ajax } from 'rxjs/ajax';
import { mergeMap } from 'rxjs/operators';

// URL for free API
const API_URL = 'https://jsonplaceholder.typicode.com/todos/1';

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

click$
  .pipe(
    /*
     * Example using mergeMap, but switchMap is often preferred 
     * for GET requests. If no parameters are needed,
     * you could use mergeMapTo.
     * ex. mergeMapTo(ajax.getJSON(API_URL))
     */
    mergeMap(() => ajax.getJSON(API_URL))
  )
  // Output: { userId: 1, id: 1, ...}
  .subscribe(console.log);

For more information, refer to the RXJS documentation: https://www.learnrxjs.io/operators/transformation/mergemap.html

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What are some creative ways to design the mat paginator in Angular?

Looking for tips on how to style Angular Material Paginator to match a Figma design? ...

Attempting to test the PactV3 GraphQL endpoint leads to failure as it is met with a 500 Internal Server Error

Currently, I am facing a challenge with creating a Pact on the consumer side using Pact-JS. I have noticed that in PactJS v3, the .withQuery method has been removed and support for GraphQL testing is not available as well. Although it should be possible t ...

In React Router v6, you can now include a custom parameter in createBrowserRouter

Hey there! I'm currently diving into react router v6 and struggling to add custom params in the route object. Unfortunately, I haven't been able to find any examples of how to do it. const AdminRoutes: FunctionComponent = () => { const ...

What is the process of integrating an MVC View into the template URI of a typescript component?

I am currently working on a project using MVC core and AngularJS2 with TypeScript. I recently added a new component (View located in Views\Home\Default.cshml) but I am encountering some issues. Below is the code I have tried: import { Componen ...

Live reload functionality in Webpack is currently not functioning as expected when utilized with the Angular

Recently purchased a template that incorporates Angular. I diligently followed all the initial setup steps, but encountered an issue with live reloading once I started making changes to the project. It is also worth noting that the project utilizes Webpa ...

NodeJS and TypeScript are throwing an error with code TS2339, stating that the property 'timeOrigin' is not found on the type 'Performance'

I am currently working on a NodeJS/TypeScript application that utilizes Selenium WebDriver. Here is an excerpt from the code: import { WebDriver } from "selenium-webdriver"; export class MyClass { public async getTimeOrigin(driver: WebDriver ...

When Angular 5 is loaded, the select list on the page will automatically display the matching option that

I am currently working on a form that is read-only and showcases data retrieved upon loading the page. One of the sections in this form includes an IsActive dropdownlist with options True or False. I have set up my model property isActive to bind with the ...

Why does IntelliJ IDEA 2016 show an error for using the [ngSwitch] attribute in this Angular2 template?

Every time I run precommit inspections, I receive a barrage of warnings even though everything seems to be functioning properly. The warnings include: Warning:(8, 58) Attribute [ngSwitch] is not allowed here Warning:(9, 42) Attribute [attr.for] is not all ...

What is the best way to initialize a discriminated union in TypeScript using a given type?

Looking at the discriminated union named MyUnion, the aim is to invoke a function called createMyUnionObject using one of the specified types within MyUnion. Additionally, a suitable value for the value must be provided with the correct type. type MyUnion ...

When the page is reloaded, establish the default value for the dropdown in Angular 9

My HTML file includes the use of p-dropdown: <p-dropdown id="userType" name="userType" inputId="userType" formControlName="userType" [required]="true" [tabindex]="1" optionLabe ...

Is it possible to utilize the lighten css property within ngStyle in Angular?

Having some trouble with the lighten property in ngStyle and it's not working as expected. I have a color variable within my component that I want to utilize like so: <div [ngStyle]="{color: schedule.group.color, background: 'lighten(' ...

Refreshing Angular 2 + Firebase app causes user to be logged out

Just diving into Angular2, Firebase, and SPAs for the first time. I've been tasked with enhancing a Angular2 (with Firebase email&pw auth) application by adding some new features. The app primarily consists of a blog (main page), a shop (/shop), a ...

What is the process for changing a field in a document on firestore?

Is there a way to modify a specific field in a firestore document without retrieving the entire document beforehand? ...

Troubleshooting: Angular version 4.3 Interceptor malfunctioning

I have been trying to implement new interceptors in Angular 4.3 to set the authorization header for all requests, but it doesn't seem to be working. I placed a breakpoint inside the interceptor's 'intercept' method, but the browser didn ...

How can I set up a KeyboardEvent listener in JavaScript?

My attempt to use @keydown resulted in an error: Type 'Event | KeyboardEvent' is not assignable to type 'KeyboardEvent'. Type 'Event' is missing the following properties from type 'KeyboardEvent': altKey, c ...

Merge topics together in RxJS like zip

Is it possible to create an observable that combines two subjects in a unique way, different from the zip function? The goal is to combine two subjects so that when both have emitted values, the latest of their values is emitted. Then, after both emit at ...

Unable to access any pages using the angular-cli http-server for deployment

When I run my project using 'ng serve', everything works fine. However, when I deploy it on a server using 'http-server ./dist', none of the pages can be accessed and an error message is displayed: host:~/morange/project$ http-server . ...

Retrieve fresh information every 30 seconds utilizing the useQuery hook in React

I am utilizing '@tanstack/react-query' to retrieve data in my React + Typescript application. Below is a snippet of my code, where I aim to fetch metric data every 30 seconds import { useQuery } from '@tanstack/react-query'; import ...

Error message encountered: Missing property status in TypeScript code

An error occurs in the refetchInterval when accessing data.status, with a message saying "property status does not exist" chatwrapper.tsx const ChatWrapper = ({ fileId }: ChatWrapperProps) => { const { data, isLoading } = trpc.getFileUploadStatus.use ...

Removing the @Input decorator in Angular's codebase

I am currently working on an Angular project for a class, and I'm facing an issue where removing the @Input decorator from my component is causing the entire application to not load properly. import { Component, OnInit, Input } from '@angular/ ...