Using RxJS to send a series of distinct AJAX requests on an event

Suppose I have an event type, such as a click event. I need to initiate 3 separate ajax requests through this event, but I want to listen for the final result of all 3 requests.

What would be the most suitable design pattern for implementing this sequence?

The current code snippet that I am working with is outlined below:

$rootScope.$eventToObservable('selectUser')
    .throttle(500)
    .map(data => {
        return angular.copy(data.additionalArguments[0].entity);
    })
    .select(d => {
        return {
            Member: MemberService.getMember(d.ID),
            otherData: MemberService.dataOtherData(d.ID),
            Notes: MemberService.getNotes(d.ID),
            Log: MemberService.getLog(d.ID)
        }
    })
    .switchLatest() // The code encounters an error here stating that "object is not a function". This could be due to the fact that the return object is not an observable. However, I am unsure about the correct design pattern to follow in this scenario.
    .subscribe(model => {
        // It is expected that the 'model' will contain an object with the result of the 3 responses mentioned above.
        $scope.model = model;
});

Answer №1

To synchronize your requests, you can utilize the zip function. By using zip, all observables will be subscribed to and yield each time all of those observables fire. This means that when the nth item from each observable is yielded, zip will then yield its nth value, which is generated by utilizing the nth values from the original observables.

After obtaining this information, you can implement switchLatest, a function that operates on

Observable<Observable<T>>
. SwitchLatest ensures that it is always subscribed to the latest observable. When a new user is selected, switchLatest will automatically unsubscribe from any pending request and subscribe to the next one instead.

$rootScope.$eventToObservable('selectUser')
    .throttle(500)
    .map(data => {
        return angular.copy(data.additionalArguments[0].entity);
    })
    .map(entityToExpandedData).switchLatest()
    .subscribe(model => {
        $scope.model = model;
    });

function entityToExpandedData (entity) {
    return Rx.Observable
        .zip(
            MemberService.getMember(d.ID),
            MemberService.dataOtherData(d.ID),
            MemberService.getNotes(d.ID),
            MemberService.getLog(d.ID),
            makeExpandedData
        );
}

function makeExpandedData (member, otherData, notes, log) {
    return {
        member:     member,
        otherData:  otherData,
        notes:      notes,
        log:        log
    };
}

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

Guide to updating the content div on a webpage without refreshing using Google App Engine

Currently, I am in the process of developing an application using GAE with Python and my main requirement is to create a chat system where multiple users can send messages to a single recipient. I initially explored using sockets but encountered issues wh ...

Tips for showcasing images within buttons in HTML

Currently, I am working on setting up a local web server to manage various functions in my car using a RPi 4. For this project, I am incorporating libraries such as nodejs, npm, express, ejs, and rpi-gpio. My goal is to utilize rpi-gpio to operate relays ...

What sets Java classes apart from JavaScript classes?

After working with C# and Java, I decided to dive into learning javascript/node.js. However, I am facing some challenges trying to understand what is wrong with this code. Here is the snippet from my main.js file: const MyClass = require("./MyClass"); le ...

The table is empty as no data is present when utilizing DataTables along with an AJAX request for a

I've been attempting to populate a table with data from a JSON file using DataTables. However, every time the page loads, all I see in the table is "No data available in table". Here's the code snippet I'm currently working with: <table ...

Using Material-UI to implement a Link component from the react-router library

I'm having trouble integrating the <Link/> component into my material-ui AppBar. Here is my navigation class: class Navigation extends Component { constructor(props) { super(props) } render() { var styles = { appBar: { ...

Create a div element that is set to be 30 pixels smaller than its containing div

I am trying to achieve a specific layout where I have a nested div structure. The parent div has a width set in percentage (80%) and I want the child div to be slightly narrower by 30px. Can anyone provide guidance on how I can accomplish this? Do I need ...

A guide on showcasing specific data within ng-repeat by referencing another property in JSON object

After retrieving a JSON file using $http(), the structure looks something like this: [ { "sno": "3", "eventname": "hockey", "event-type": "sports", "A-team": "mme", "B-team": "eee", "Gender": "male", "time": "2017-11-24 00:00:00", "isres ...

Angular allows for the dynamic inclusion and exclusion of components, providing a flexible

In my setup, I have a container that houses two distinct components. The first component receives a list of users from the backend. Upon clicking on a specific user, I aim to display all of their detailed information in the main container of the second co ...

Create an interactive Chart.js displaying real-time data fetched through ajax requests, designed to be fully responsive. Addressing

Chart.js (http://www.chartjs.org/docs/) is the tool I'm using for charting purposes. I am looking to retrieve data from an Ajax request while ensuring that the chart is responsive. Within my HTML markup, I've included a canvas element like this ...

Using the keyword "this" in JavaScript for manipulating the DOM

Struggling to grasp the concept of using the keyword "this" for DOM manipulation in JavaScript? I could really use some help understanding it better. Consider this basic program: <!DOCTYPE html> <html> <head> <title>JavaScript ...

Error encountered while running npm build command for HTML Webpack Plugin

As a newcomer to webpack, I'm currently attempting to integrate it into a project that utilizes the Cesium JS API. Following the online tutorial provided by Cesium, my process hits an unexpected roadblock when running the command "npm run build." The ...

I encountered an issue where my button's onClick function was not functioning properly with the clickable component

Here is my display I have a component(Product) that can be clicked. One of its children is also a button. However, when I click it, the Product's function runs. How can I make sure my button executes separately? <ProductForm> ...

hyperlinked text that automatically updates with the current date (using metarefresh)

I want to insert a date variable into a URL based on the current date. Specifically, I am looking to create a link from SharePoint that directs a user to the relevant files in a shared drive. My initial idea is to use an HTML page with a meta refresh that ...

When the "open" prop is set to "true", the DRAWER component from @material-ui/core fails to display

Help Needed: I'm struggling to make the drawer component open when the variant prop is set to "temporary". Material-UI Package Used: @material-ui/core I have integrated Material UI's drawer component into my custom Nav component. However, I am ...

Is it possible to dynamically pass a component to a generic component in React?

Currently using Angular2+ and in need of passing a content component to a generic modal component. Which Component Should Pass the Content Component? openModal() { // open the modal component const modalRef = this.modalService.open(NgbdModalCompo ...

A guide on invoking a web method from an aspx.vb page in VB.net

My goal is to call a WebMethod from my aspx.vb file. Below is the syntax of my WebMethod located in Default.aspx.vb: <System.Web.Services.WebMethod()> _ <ScriptMethod(UseHttpGet:=True, ResponseFormat=ResponseFormat.Json)> _ Public Shared Funct ...

Encountering an issue where rendering a component named Exercise within the ExerciseList component is not allowed

The ExerciseList component is designed to display all the exercises that can be edited or deleted from the list. It returns the Exercise Component or function for this purpose. If anyone could take a look and help identify any mistakes in my code, it would ...

Navigable Vuetify Tabs with routing capabilities

Within my Vue application, I have a page that contains various tabs. My goal is to display different tabs based on the routes being accessed. To achieve this functionality, I followed an answer provided in this link. Overall, it's working well! I ca ...

Displaying the Status of a Script that is Running Asynchronously

My script takes around 5 minutes to complete and sends an email with a file attachment once finished. The entire process happens on a single PHP page without using AJAX. I want the front end to handle form submission seamlessly, processing the request in ...

Tips for creating tree diagrams for JSON data with D3.js?

I am eager to represent intricate nested JSON objects as tree diagrams using D3.js. Most examples utilize JSON files that explicitly outline their hierarchy, such as through the children attribute: { "name":"Alex", "children& ...