Angular 2: Patience is a Virtue When Dealing with Observables

Dealing with multiple asynchronous calls can be tricky, especially when you need to wait for all of them to finish before moving on to the next step. In my case, I have separate calls that may or may not be made depending on user input. How can I efficiently handle this situation?

submitButton_Clicked() {
  this.busy = this.service.call1() // must be called
    .first().subscribe(
      if (success){

        // **Logic to decide if call 2 is needed**
        ...

        this.busy = this.service.call2() // might be called
          .first().subscribe();

        // **Logic to decide if call 3 is needed**
        ...

        this.busy = this.service.call3() // might be called
          .first().subscribe();

        this.router('route'); // should route after all potential calls
      }
    );   
}

As I'm still learning about observables, I'm a bit unsure about the best approach to solve this. Any guidance would be greatly appreciated. Thank you!

Answer №1

To utilize flatMap, you can:

let Observable = Rx.Observable;

let f = Observable.of(20).delay(1000);
let g = f.map(x => x*x)
  .flatMap(x => Observable.of(x + 100));

g.subscribe(console.log);


/** 
 * Rx.Observable.prototype.flatMap 
 * and Rx.Observable.prototype.selectMany 
 * are equivalent.
 */

let h = f.map(x => x*3)
  .delay(1000)
  .flatMap(x => Observable.of(x + 100));
h.subscribe(console.log);

https://jsbin.com/vokofug/edit?js,console,output

Alternatively, you can use concat or merge:

The concat() stream will display values from source1 first, then from source2 after source1 completes.

The merge() stream will display values from source1 and source2 as they are emitted, not waiting for the first stream to complete before emitting values from the second.

http://codepen.io/SitePoint/pen/PzKdVQ

'use strict';

const source1 =
  Rx.Observable.interval(100)
    .map(val => `Source 1: ${val}`)
    .take(5);

const source2 =
  Rx.Observable.interval(100)
    .map(val => `Source 2: ${val * 10}`)
    .take(5);

const concat_table = $('#concat-table-body'),
      merge_table  = $('#merge-table-body');

source1
  .concat(source2)
  .subscribe(value => {
    const row = document.createElement('tr');
    row.innerHTML = value;

    // Source 1 values populate BEFORE Source 2 
    concat_table.append(row);
  });

source1
  .merge(source2)
  .subscribe(value => {
    const row = document.createElement('tr');
    row.innerHTML = value;

    // Source 1 values INTERLEAVE with Source 2
    merge_table.append(row);
  });

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

Running into issues with TypeScript in conjunction with Redux-Form and React-Redux connect

My excitement for TypeScript grew until I encountered some frustrating incompatibilities between Redux-Form and React-Redux. I am aiming to wrap a component decorated with reduxForm using the connect decorator from react-redux—this method has always bee ...

Generate a random string and return it as a value

I am looking to incorporate JavaScript code into my Angular application. I attempted the following approach: export class MerchantNewComponent extends FormBaseComponent { constructor(private merchantService: MerchantService, private route ...

Exploring the World of Angular6 with the Incredible Power of tinyMCE Editor

Hello, I'm looking to incorporate the tinyMCE editor into my Angular 6 application. I followed a thread that explains how to integrate it, but I ran into an issue where it says the domain is not registered. I would prefer to do this without requiring ...

Enhance your text in TextInput by incorporating newline characters with advanced editing features

I'm encountering an issue with my Textarea component that handles Markdown headers: type TextareaProps = { initValue: string; style?: StyleProp<TextStyle>; onChange?: (value: string) => void; }; type OnChangeFun = NativeSynthetic ...

Transferring information from childA component through its parent component and into childB component

In my project, there is a main parent component with two child components: 1. app-search-list and 2. app-vertical-menu The data is passed from the app-search-list (childA) component to its parent component, and then from the parent to the app-vertical-men ...

Contrast between the node modules "highcharts-angular" and "angular-highcharts" for Angular version 7

In my upcoming Angular v7 application using the latest version of Highcharts, I have encountered two similar node modules listed on the HighCharts tutorial page. However, I'm unsure of the differences between them: Node module: highcharts-angular No ...

Substitute this.bindMethod for function component

I have a class component that is structured like this: interface MyProps { addingCoord: any resetCoords: any } interface MyState { x: any y: any } class DrawerOld extends React.Component<MyProps, MyState> { width: number height: number ...

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 ...

Is it feasible to update just one key within an exported type using setState in TypeScript?

Recently, I decided to dive into Typescript within my React App and encountered an error that has left me stumped. I'm wondering if it's possible to access a specific key in an exported type and modify its value? Here is how I've exported ...

Encountering an error with loading %5Bobject%20Object%5D on a webpack-generated JavaScript file hosted in an express server because of Stylus styles

I have been experimenting with enhancing the example linked here. Initially, everything worked smoothly when I used npm start. However, I wanted to integrate it into an existing ExpressJS project. To achieve this quickly, I copied the three js files to the ...

What is the process for integrating an extension function into an Express response using TypeScript?

I am looking to enhance the Response object in Express by adding custom functions. Specifically, I want to introduce a function: sendError(statusCode: number, errorMessage: string) which can be called from anywhere like this: response.sendError(500, &qu ...

Managing sessions between Node.js and Angular with JSON Web Tokens

I am currently developing an application where NodeJS serves as the backend, handling all business logic and exposing JSON REST services for consumption by the Angular 4 app which acts as a simple client. While this setup seems to be working well, I am fac ...

How to eliminate certain elements from the DOM in Angular 5

I'm facing a minor issue in my Angular/Typescript project that I can't seem to resolve. I am still new to these technologies and struggling with removing certain DOM elements. The content is auto-generated with specific CSS classes, and unfortuna ...

Tips for converting mat-paginator in Angular 4?

Can you provide any suggestions on how to translate the phrase "Items per page" within the Angular mat-paginator tag, which is a component of Material Design? ...

Typescript not being transpiled by Webpack

As I set out to create a basic website, I opted to utilize webpack for packaging. TypeScript and SASS were my choice of tools due to their familiarity from daily use. Following the documentation at https://webpack.js.org, I encountered issues with loaders ...

Encountering failures while running Angular tests in GitHub Actions due to reading inner text (which works fine locally)

I am facing an issue in my GitHub actions workflow where Karma is unable to read the 'innerText' of a native element for an Angular project. The error 'TypeError: Cannot read properties of null (reading 'innerText')' is being ...

How to set up npm to utilize the maven directory format and deploy war files

Embarking on my very first pure front-end project, I decided to deploy it using Java/Maven. To begin, I set up a standard WAR project: │ package.json │ pom.xml │ tsconfig.json │ typings.json │ │ ├───src │ └───main ...

Adjusting the dimensions of the cropper for optimal image cropping

I am currently working on integrating an image cropper component into my project, using the react-cropper package. However, I am facing a challenge in defining a fixed width and height for the cropper box such as "width:200px; height:300px;" impo ...

Encountered an error trying to access '0' property of an undefined object when iterating through data in angular framework

My API is returning data in the format shown below: "fileName": "data.txt", "onlyInFile1": [ { "_id": "60618e87c2077428e4fedde5", "TERMINAL_ID": "Y6152114", "EXTERNAL_STAN": & ...

Issue arises when attempting to use the useEffect hook in React with Typescript to reset states upon the component unmounting

I'm facing an issue with my useEffect cleanup when the component unmounts and setting states simultaneously. My code involves selecting a client by clicking on them and setting their ID to send in an API request: const setClient = () => { setC ...