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

`The utilization of a collective interface/data type within an Angular application`

I created a HeaderComponent that requires an object with the structure of {title: string, short_desc: string} as its input property. @Component({ selector: 'header', templateUrl: './header.component.html', styleUrls: ['./hea ...

Getting the Correct Nested Type in TypeScript Conditional Types for Iterables

In my quest to create a type called GoodNestedIterableType, I aim to transform something from Iterable<Iterable<A>> to just A. To illustrate, let's consider the following code snippet: const arr = [ [1, 2, 3], [4, 5, 6], ] type GoodN ...

Attempting to publish and install a unique angular2 component using NPM and Angular-CLI results in successful compilation only on the initial try

I am facing a peculiar and frustrating issue. The problem revolves around an Ng2 component I have developed called via-date-picker. My goal is to publish it on NPM so that it can be easily utilized in other projects. To achieve this, I converted it into a ...

Fixing the issue of the Put method not successfully updating MongoDB when using Angular7 with NodeJS on the

Currently, I am facing an issue with my Angular7 application that is connected to NodeJS and MongoDB on the backend. After testing the put method using Postman, it seemed to work perfectly. However, the problem seems to be within the Angular service compon ...

Tips for submitting a form with AngularJS version 4

I am developing a single page application using AngularJS 4. Can anyone guide me on how to submit a form upon clicking the submit button in AngularJS 4? Your help is greatly appreciated. Thank you! ...

Support for dark mode in Svelte with Typescript and TailwindCSS is now available

I'm currently working on a Svelte3 project and I'm struggling to enable DarkMode support with TailwindCSS. According to the documentation, it should be working locally? The project is pretty standard at the moment, with Tailwind, Typescript, and ...

React approach for managing multiple combobox values

Currently, I'm working on a page where users can upload multiple files and then select the file type for each file from a dropdown menu before submitting. These 'reports' are the uploaded files that are displayed in rows, allowing users to c ...

Filling the text and value array using a collection of objects

Need help with populating an array of text and value using an array of objects in Angular. Below is the JSON data containing the array of objects. Declaration public AuditYearEnd: Array<{ text: string, value: number }>; Assignment - How can I assi ...

Typescript raises an issue regarding a React component's optional prop potentially being undefined

I have a basic React component that looks like this: interface ComponentProperties { onClick?: () => void; } const CustomComponent = (properties: ComponentProperties) => { if (!properties.onClick) { return <></>; } ...

How can a mock document be utilized in a unit test for an imported TypeScript dependency?

To effectively unit-test a legacy TypeScript class, I am seeking ways to mock the document object. The class has dependencies on another class (View.ts), which in turn relies on a 3rd party module that further depends on the existence of the document. The ...

How can I effectively utilize the Metamask SDK with TypeScript?

Currently, I am in the process of developing a webpack+pnpm+typescript+react website. All the versions being used are LTS and my preferred IDE is VSCode. According to the guide provided by Metamask here, it seems like I need to follow these steps: npm i @m ...

Discover the utility of the useHistory() hook in TypeScript for Class Components

Hello there, I am currently attempting to implement the following code snippet in my TypeScript-based class component: this.history.push({ pathname: `/search-results`, search: `${job}$${location}` } ...

Resolving the error message "Default props must have construct or call signatures for 'Component' in Typescript"

I'm currently working on a function component called MyComponent and I'm facing an issue with setting a default prop for component. The goal is to have the root node render as a "span" if no value is provided. However, I am encountering the follo ...

Upon hovering, icons for each project name are displayed when `mouseenter` event is triggered

My issue lies with the mouseenter function. I am trying to display icons specific to the project name I hover over, but currently, it displays icons for all projects at once. I want each project hovered over to show me its respective icons Below is some c ...

The attribute 'title' cannot be found within the type 'IntrinsicAttributes & IProps'

Hello, I am currently facing an issue where I am trying to hide an item in a different view using interfaces. The specific error I am encountering is mentioned in the title of this query. Let me provide you with part of the code to give you more context: ...

Tips for simulating behavior in express using Typescript and the Mocha library

Help with mocking 'Request' in Mocha using express with Typescript needed! Here is the current approach: describe("Authorization middleware", () => { it("Fails when no authorization header", () => { const req = { ...

Guide on deactivating the div in angular using ngClass based on a boolean value

displayData = [ { status: 'CLOSED', ack: false }, { status: 'ESCALATED', ack: false }, { status: 'ACK', ack: false }, { status: 'ACK', ack: true }, { status: 'NEW', ack ...

Angular - Display shows previous and current data values

My Angular application has a variable called modelResponse that gets updated with new values and prints them. However, in the HTML, it also displays all of its old values along with the new ones. I used two-way data binding on modelResponse in the HTML [( ...

What is the best way to troubleshoot a quasar typescript file type error?

Currently, I am delving into Quasar using TypeScript and encountering a type error while working on file uploads. Here is the snippet of my code where the type error arises specifically in the parameter of the form.append() method. The error message read ...

Adding a tooltip to an Angular Material stepper step is a great way to provide

I am trying to implement tooltips on hover for each step in a stepper component. However, I have encountered an issue where the matTooltip directive does not seem to work with the mat-step element. <mat-horizontal-stepper #stepper> <mat-step lab ...