Trouble encountered when using RxJS zip and pipe together

In my Angular Resolver, I am facing a scenario where I need to wait for two server calls. The catch is that the second server call is optional and can be skipped based on user input. This data retrieval process is crucial for loading the next page seamlessly.

The problem lies in my zip function as it fails to reach the pipe section, which results in me being stuck in the resolver. Here's the step-by-step procedure:

  1. Combine the requests using zip

  2. Process them through a pipe

  3. Return an observable to the resolve function

Below is the snippet of my code:

public resolve(route: ActivatedRouteSnapshot, state: RouterStateSnapshot):
    Observable<any> | Promise<any> { //

    const id = +route.paramMap.get('id');
    const wantsSecondRequest = +route.paramMap.get('wantsSecondRequest');


    const requests: Array<Observable<any>> = new Array();

    requests.push(firstServerCallHappensHere());
    if (wantsSecondRequest === 1) {
      requests.push(secondServerCallHappensHere());
    }

    return zip(requests).pipe(take(1), mergeMap(([a, b]) => {
         // PROCESS THE REQUESTS ACCORDINGLY
          return of(a);
    }));

}

I have experimented with Promise.all and used Promises instead of Observables in the past, but encountered a roadblock when handling errors. With Promises, I couldn't prevent them from completing abruptly in case of an error, leading to undesired navigations.

Answer №1

As per the documentation provided at http://reactivex.io/documentation/operators/zip.html, the zip() function is capable of accepting multiple parameters which are observables, even though you have supplied an array. This information might prove to be useful:

public resolve(route: ActivatedRouteSnapshot, state: RouterStateSnapshot):
    Observable<any> | Promise<any> { //

    const id = +route.paramMap.get('id');
    const wantsSecondRequest = +route.paramMap.get('wantsSecondRequest');

    return zip(
      firstServerCallHappensHere(),
      wantsSecondRequest === 1 ? secondServerCallHappensHere() : undefined,
    ).pipe(take(1), mergeMap(([a, b]) => {
         // DO STUFF WITH MY REQUESTS
          return of(a);
    }));

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

Using Typescript and React to retrieve the type of a variable based on its defined type

Just getting started with Typescript and could use some guidance. Currently, I'm using React to develop a table component with the help of this library: Let's say there's a service that retrieves data: const { data, error, loading, refetc ...

What is the reason behind Q.js promises becoming asynchronous once they have been resolved?

Upon encountering the following code snippet: var deferred = Q.defer(); deferred.resolve(); var a = deferred.promise.then(function() { console.log(1); }); console.log(2); I am puzzled as to why I am seeing 2, then 1 in the console. Although I ...

Developing an Observer and sending updates to my followers

I have a function that returns an Observer for subscription. Inside this function, I make an API call which also returns an Observer to which I subscribe. Once I analyze the data received from this Observer, I need to notify my own Observer subscribers. B ...

Error in NodeJs: Port 3000 is already in use due to the utilization of socket.io and express

I've developed a node.js application using socket.io and express. The code snippet is as follows: const express=require('express'); const app=express(); const http=require('http').Server(app); app.use(express.static('public&ap ...

utilizing the data provided by a user in the "prompt" window within my HTML code

Looking to utilize user input from the prompt window. This is my custom JavaScript form: var answer; function load() { answer=prompt("what is your name?", "Write your name here"); return answer; } function hideNsee() { var HNS = docume ...

The RazorPay callback encountered an Uncaught TypeError indicating that the function is not recognized

In my TypeScript class, I have a defined handler as follows: "handler": function (response) { this.sendUserStatus(); }, Unfortunately, when I attempt to call this.sendUserStatus();, I encounter the following error: Uncaught Typ ...

Change the left position of the sliding menu in real-time

I am currently designing a website with a sliding menu feature. By default, the menu is set to -370px on the left, displaying only the "MENU" text initially. When a user hovers over the menu, it expands to the right, allowing them to select different menu ...

Implement a feature in NextJS where an MP3 file is played upon clicking

Just getting started with JS frameworks and having some trouble with the function syntax. Here's what I have so far: when the button is clicked, it should play a quick audio file specified below the button in the Audio tags. Any suggestions on how to ...

What is the best way to implement an AJAX request to update the page without having to refresh it?

My to-do app currently reloads the page when I click on "Add" in order for the changes to take effect and display the items. However, I want to implement AJAX requests so that the page does not need to refresh. Can anyone guide me on how to achieve this? ...

The act of binding is not functioning

Hello everyone, I am excited to be posting on stackoverflow for the first time. Recently, I have started learning ember.js and I am really enjoying it. Currently, I am working on a small project to practice my ember.js skills, but I seem to be having tro ...

How can Vue detect modifications made in the edited field?

I am facing an issue with tracking changes in a specific object. Here is the structure of the object: users: { email: '', password: '' } My goal is to detect any edits made to the keys within the users object and store the key ...

Utilize JavaScript/jQuery to check for upcoming deadlines in a SharePoint 2013 list

I need to check if an item is due based on its date. When a user creates an item with a date in the format MM/DD (e.g., 06/15), I want to determine if that date falls within the next 30 days, turning it red, within the next 60 days, turning it orange, or g ...

Guide on setting an instance property through a callback function triggered by the instance

I am looking to set an attribute of an angular service using the result from a callback function. Here is my Angular service: @Injectable() export class SkillsManagerService { private skill: any; private event: any; constructor() { ...

Retrieve data from an SQL database and populate an HTML dropdown menu in a web page using PHP

I am a beginner in the world of JavaScript and facing some challenges. I am working with PHP 7 and attempting to retrieve data from an SQL database, specifically a table. My goal is to extract a single column from this table and display it in a dropdown me ...

Is there a way to access the initial item in a JavaScript array?

Recently, I've been delving into the world of javascript and encountered a task that involves removing the first item from an array. Solution One function getFirst(arr, item) { arr.push(item); var removed = arr.shift(); return removed; } S ...

eachSeries not executing the callback

I am encountering an issue with async.eachSeries. I am using it to loop through an array and download files using a specific function (refer to the source code provided). However, I am having trouble as the callback never seems to be called. Is there somet ...

Refining to Showcase One Menu Selection

I am having an issue with my bootstrap menu that includes a search field. The problem is that when I try to filter the dropdown menu using the search field, it filters all dropdown items instead of just the one I want. For example, if I search for a term f ...

Creating a union type from an array that is not a literal (using `Object.keys` and `Array.map`)

Can a union be derived from a non-literal array? I attempted the following: const tokens = { "--prefix-apple": "apple", "--prefix-orange": "orange" }; const tokenNames = Object.keys(tokens).map(token => toke ...

Stripping CSS prefixes upon file initialization

When developing my application, I have a process in place where I load CSS files on the back-end using Express.JS and then transmit them to the front-end. However, before sending the CSS code to the front-end, I need to: Identify the user's browser; ...

Exploring the Concept of Extending Generic Constraints in TypeScript

I want to create a versatile function that can handle sub-types of a base class and return a promise that resolves to an instance of the specified class. The code snippet below demonstrates my objective: class foo {} class bar extends foo {} const someBar ...