The flatMap function is not operating as intended in the sequence of function calls

Having difficulty organizing a chain of calls using TypeScript with RxJS observables

I am new to RXJS and I am struggling to structure a chain of calls in my TypeScript code. My question is - how can I ensure that this.http.get(''); is only called once? Please note that the code provided is just a simplified example for demonstration purposes.

import {Injectable} from '@angular/core';
import {flatMap, map} from 'rxjs/operators';
import {Observable, from} from 'rxjs';
import {HttpClient} from '@angular/common/http';

@Injectable()
export class CoolService {

  constructor(private http: HttpClient) {}
  x(): Observable<Object> {
    return from(Promise.resolve({a: {b: 'c'}})).pipe(
      flatMap((x) => {
        console.log(x);
        return this.http.get('http://www.gooogle.com');
      }), map((res) => {
        console.log(res);
        return res;
      }));
  }
}


Answer №1

My misconception arose from a lack of understanding about how rxjs operators operate individually for each subscription, instead of performing one calculation for all subscriptions simultaneously. This led me to mistakenly chain calls in the service and subscribe to responses in different locations. It turns out that operators execute as many times as there are subscriptions in the code, prompting me to rethink and restructure my approach.

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

Why aren't my arrays' characteristics being recognized when I create an instance of this class?

There is a puzzling issue with the arrays in my class. Despite creating them, when I try to access them in another class they are not recognized, only the otherProp is visible. To make matters worse, attempting to add elements to the arrays results in an ...

Angular - Javascript - Oops! The variable 'google' seems to have gone missing after reloading the page

For my website, I utilized Angular 2+ and integrated the Google Maps Api by adding the following code to my index.html file: <script async defer src="//maps.googleapis.com/maps/api/js?[myKey]&libraries=places"> </script> ...

Is it possible to invoke Cucumber stepDefinitions from a separate project at the same directory level?

Currently, I have a project called integration_test that includes all test projects utilizing cucumberjs, typescript, and nodejs. Project1 contains the login implementation, and I would like to use this implementation in Scenarios from Project2 and Projec ...

How to pass props to customize styles in MUI5 using TypeScript

Currently, I'm in the process of migrating my MUI4 code to MUI5. In my MUI4 implementation, I have: import { createStyles, makeStyles } from '@material-ui/core'; import { Theme } from '@material-ui/core/styles/createMuiTheme'; ty ...

Tips for enhancing a table with extra functionality in Angular 6

Hi there! I've created a table using Angular 6 and now I'm looking to enhance it with some extra functionality: Implement an overall table search feature Allow users to sort the table by columns Add a "Page x of n" option for pagination I woul ...

Type of Data for Material UI's Selection Component

In my code, I am utilizing Material UI's Select component, which functions as a drop-down menu. Here is an example of how I am using it: const [criteria, setCriteria] = useState(''); ... let ShowUsers = () => { console.log('Wor ...

Incorporate FontAwesome icons into table headers within an Angular framework

I am attempting to customize the icons for sorting in my table headers by following the guidelines laid out in the ng-bootstrap table tutorial. The NgbdSortableHeader directive plays a key role in changing the sorting of columns: @Directive({ selector: ...

In Angular, you can easily modify and refresh an array item that is sourced from a JSON file by following these steps

Currently, I am working on implementing an edit functionality that will update the object by adding new data and deleting the old data upon updating. Specifically, I am focusing on editing and updating only the comments$. Although I am able to retrieve th ...

Using Typescript to create an interface that extends another interface and includes nested properties

Here is an example of an interface I am working with: export interface Module { name: string; data: any; structure: { icon: string; label: string; ... } } I am looking to extend this interface by adding new properties to the 'str ...

Refreshing Datatable in Angular 2 - Trouble with dtInstance.then error

I'm currently working on an Angular 2 application where I have a component that includes both a dropdown list and a datatable. The requirement is to display details in the table based on the name selected from the dropdown list. HTML - <div> ...

Move the assets folder in Angular to Azure Storage

Looking to streamline my Angular application by transferring all the assets to Azure Storage. Rationale: The assets folder in my repository is cluttered with large, static files that never change. Since we are hosted on Azure, the plan is to move the ass ...

Getting around using Material-UI Icons

Is it possible to utilize a Material-UI Icon for navigation using React Router Dom? I attempted the following approach without success: <NavigateBeforeIcon path="/vehicles"></NavigateBeforeIcon> With buttons, I am able to use component={Link ...

Adjust the transparency and add animation effects using React JS

When working on a React project, I encountered an issue where a square would appear under a paragraph when hovered over and disappear when no longer hovered. However, the transition was too abrupt for my liking, so I decided to implement a smoother change ...

Updating a component in Angular 4.3.1 from within an observable callback

My Project Journey I am currently immersing myself in learning Angular by working on a personal project: developing a game that involves routing, services, and more. One of the requirements is to hide the header on the landing page (route for '/&apos ...

The value of the filename property cannot be determined as it is undefined

Hey everyone, I'm currently working on a project using nestjs and reactjs. I encountered an error when trying to add a document that reads: "Cannot read properties of undefined (reading 'filename') in multer.config.ts" import { diskStorag ...

Experiencing difficulties establishing a connection with my NodeJs server socket and TypeScript

I've been struggling to run the code from this post and I really need some help. The code can be found at: https://medium.com/@mogold/nodejs-socket-io-express-multiple-modules-13f9f7daed4c. I liked the code as it seems suitable for large projects, but ...

Issue: subscribe function is not definedDescription: There seems to be an

I'm currently trying to retrieve a value from an array based on a specific element, and then finding the exact matching element. Unfortunately, I've encountered an error with this.getProduct(name1: string) function even though I have already impo ...

Dragging and dropping in Angular does not move to the intended location within a mat dialog

Attempting to manipulate the order of a lengthy list by dragging and dropping items. In a basic component, moving an item is uncomplicated - able to drag it anywhere within the list. While dragging, can scroll through contents beyond visible range and dro ...

How do I assign a default value to an optional parameter in a derived class in Typescript?

One of my classes is called ClientBase: export class ClientBase { constructor(private uri: string, private httpClient: HttpClient) { } // Contains Various Methods } I have multiple subclasses that are derived from the ClientBase For instance: @I ...

Encountering issues with importing a module from a .ts file

Although I have experience building reactJS projects in the past, this time I decided to use Node for a specific task that required running a command from the command line. However, I am currently facing difficulties with importing functions from other fil ...