Utilizing RXJS in Angular to pull information from numerous services within a single component

There are two services, ser1 and ser2.

  getdata1() {
    this.http.get<{message:string,Data1:any}>('http://localhost:3000/api/1')
      .pipe(map((data1)=>{
        return Data1.Data1.map(data=>{
          return  {
            id: data._id,
            data1Title:data1.data1Title,
          }
        })
      })).subscribe((data1) => {
        this.data1=data1
        this.serv1Subject.next([...this.data1])
      })
  }

  getData1Listener() {
    return this.serv1Subject.asObservable()
  }

For ser2:

  getdata2() {
    this.http.get<{message:string,Data2:any}>('http://localhost:3000/api/2')
      .pipe(map((data2)=>{
        return Data2.Data2.map(data=>{
          return  {
            id: data._id,
            data2Title:data2.data1Title,
          }
        })
      })).subscribe((data2) => {
        this.data2=data2
        this.serv2Subject.next([...this.data2])
      })
  }

  getData2Listener() {
    return this.serv2Subject.asObservable()
  }

For componentX, the data1 and data2 need to be fetched in ngOnInit, and functionY needs to be triggered when the data is available.

To trigger functionY using subscribe in componentx.ts:

ngOnInit() {
    this.Service1OberableSubject = this.serv1.getData1Listener().subscribe((data1) => {
      this.data1 = data1;
    })
    this.Service2OberableSubject = this.serv2.getData2Listener().subscribe((data2) => {
      this.data2 = data2;
    })
    this.serv1.getdata1()
    this.serv2.getdata2()
  }

Answer №1

Perhaps an approach similar to this. Utilize tap to intercept the response and perform any necessary actions. Additionally, forkJoin will combine the responses and provide them in an array, with the first index containing the response from the initial observable.

fetchData1() {
    this.http.get<{message:string,Data1:any}>('http://localhost:3000/api/1').pipe(
        map((data1)=>{
            return Data1.Data1.map(data=>{
                return {
                    id: data._id,
                    data1Title:data1.data1Title,
                }
            })
        }),
        tap((data1)=>{
            //store data1 if necessary
            this.serv1Subject.next([...this.data1]))
        })
    )
}

fetchData2() {
    this.http.get<{message:string,Data2:any}>('http://localhost:3000/api/2').pipe(
        map((data2)=>{
            return Data2.Data2.map(data=>{
                return  {
                    id: data._id,
                    data2Title:data2.data2Title,
                }
            })
        }),
        tap((data2)=>{
            //store data2 if necessary
            this.serv2Subject.next([...this.data2]))
        })
    )
}

forkJoin(
    fetchData1(),
    fetchData2()
).subscribe((x:any[])=>this.handleData(x));

function handleData([a, b]){
    console.log({a: a,b: b});
}

Answer №2

To efficiently combine multiple HTTP requests in Angular, you can utilize the forkJoin method from the rxjs library.

import { forkJoin } from 'rxjs';

app.component.ts

ngOnInit() {
  forkJoin([this.service1.getPosts(), this.service2.getComments()]).subscribe(response => {
    this.posts = response[0];
    this.comments = response[1];
  });
}

Answer №3

Check out this code snippet that demonstrates how to efficiently utilize an if statement:

import { merge } from 'rxjs';
import { filter } from 'rxjs/operators';

ngOnInit() {

  this.service1.fetchData()
  this.service2.retrieveData()

  merge(this.service1.dataListener(), this.service2.dataListener())
  .pipe(filter())
  .subscribe(([result1, result2]) => {
     this.result1 = result1;
     this.result2 = result2;

     customFunction(result1, result2)
  })

}

Answer №4

forkJoin stands out as the top choice in this particular scenario. However, it is crucial to also grasp the functionality of other high-order operators as they can prove to be beneficial in various situations. For example:

concatMap — enables the mapping of observables in a sequential fashion, waiting for each previous observable to complete. It is ideal for scenarios like saving form data in sequence.

mergeMap — facilitates parallel mapping of observables, keeping all preceding Observables active simultaneously.

switchMap — is recommended for cancelling previous subscriptions when needed. It works exceptionally well when implementing features like type-ahead search, in conjunction with debouncing and avoiding duplicate values.

exhaustMap — effectively disregards newly emitted values until the ongoing observable is finished. This operator shines when handling scenarios like saving data upon button click, possibly clicked multiple times.

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

What could be causing my newsletter form to malfunction on Amazon CloudFront?

I'm currently working with HTML on an Amazon EC2 instance (Linux free tier). I want to integrate CloudFront into my setup, but I'm encountering issues with my newsletter functionality. Despite not being an expert in AWS, I am struggling to unders ...

How can I transfer request headers from Express to index.js in React?

Is there a way to store user-related information received in the request headers of the Express server as a runtime variable accessible in index.js? I need to apply conditional routing based on these parameters. Alternatively, is there a way to pass these ...

After compiling the code, a mysterious TypeScript error pops up out of nowhere, despite no errors being

Currently, I am delving into the world of TypeScript and below you can find the code that I have been working on: const addNumbers = (a: number, b: number) => { return a + b } Before compiling the file using the command -> tsc index.ts, the ...

Tiny adjustment to jQuery Collapsible Panel

I have successfully implemented a jQuery Accordion in my demo. When I click on 'About Us', it reveals the 'Team' link below. Exciting! Now, I am wondering if it is possible for this Accordion to function without needing the 'item& ...

Guide on retrieving the value of "form" from a select using jQuery in a Ruby on Rails application

I am struggling to figure out how to use jQuery to pass the value of the form attribute from the select tag. I have been trying different ways, but so far haven't been successful. When using simple_form_for, the input statement looks like this: < ...

AngularJS: Display the last four characters of a string and substitute the rest with 'X'

I am attempting to change the characters with X and make it look something like this XXXXXT123 This is what I have tried: var sno = 'TEST123'; alert(sno.slice(0,3).replaceWith('X')); However, I encountered an error in the console ...

Why does ng-bind fail to display values from rootScope that have been set by using ng-click?

I am trying to save a variable within $rootScope. When I have the following structure, everything works fine and the second div displays the value: <html ng-app> ... <body> <button ng-click="$rootScope.pr = !$rootScope.pr"></b ...

Unable to display menu content text using jQuery

Currently experimenting with jQuery to create a dynamic submenu. The goal is to have a sub menu appear when the main menu is clicked, and then disappear when an item in the sub menu is selected, revealing additional information within a div. Unfortunately, ...

Extract the year from a string formatted as 1880-01-01T00:00:00.000

Looking to extract the year from an array of dates with format 1880-01-01T00:00:00.000. What's the most efficient method to accomplish this using JavaScript? ...

Encountered a setback while trying to add information to a MySql database through Express

When I try to execute an insert query on a database, it throws the following error: code: 'ER_PARSE_ERROR', errno: 1064, sqlMessage: 'You have an error in your SQL syntax; check the manual that corresponds to your MySQL server versio ...

using post request axios to send parameters

I am looking to make a post request using axios with an object as the payload. employee:{ name: 'test', email: '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="0d79687e794d6a606c6461236e6260">[email ...

Tips for setting up a Vue.js property as an array type element

To begin, I am looking to initialize the properties of image, description, video, and title with the corresponding fields from the first element in the variants array. The variants array is retrieved by sending an AJAX request that returns a JSON file. ...

Adjusting the transparency of TabBadge in Ionic 2

I am currently working on a project that involves tabs, and I'm looking to update the style of the badge when the value is 0. Unfortunately, I am unsure how to dynamically change the style of my tabs or adjust the opacity of the badge in the style. M ...

The perfect way to override jest mocks that are specified in the "__mocks__" directory

Within the module fetchStuff, I have a mock function named registerAccount that is responsible for fetching data from an API. To test this mock function, I've created a mock file called __mocks__/fetchStuff.ts. Everything seems to be functioning corre ...

The onClick event cannot be triggered within a div that is generated dynamically

I am having an issue with a jquery code that dynamically generates a div. The problem I'm facing is that the onclick function for the anchor tag is not calling the required function. Below is the code snippet: $("#new").append(' <ul cla ...

Learn how to insert a <TableRow> in a for loop using Object.keys

<TableBody> {(() => { var result = []; let key = Object.keys(genericResultList)[1]; var list = genericResultList[key]; for (var i = 0; i < list.length; i++) { ***\<!-- Add in the \<T ...

Automating the creation of box UVW maps through programming

I'm looking for a way to automatically create box UVW maps in 3D models, similar to the functionality of UVW Map -> Box in programs like 3ds Max. Here's an example with the default UV mapping And here is an example with the desired box UV ma ...

[Web Development]:

Having an issue with my HTML file where a JavaScript function named "CheckCaptcha" is not being executed when an image is clicked. I've been working on the code for hours, trying different tweaks and modifications, but it still can't seem to find ...

Directive in AngularJS is a reusable component that allows

Let me explain my situation. I am dynamically adding a block of code using JavaScript and binding it to my AngularJS scope. Everything seems to be working fine, except for one issue. There is a directive on a text box that works properly. However, the $wat ...

Is there a way to store the outcome of my node api request in a variable and then transmit it using Express?

Currently, I am leveraging Node to initiate an API call to a movie database. This Node API call is enclosed within an Express route. // Mandatory module requirements var express = require('express'); var router = require('./router.js&ap ...