Performing an RxJS loop to retrieve the httpGet response, followed by executing httpPut and httpPost requests based

I am currently working on a UI form that allows users to update or add translation text.

To achieve this, I need to create an rxjs statement that will perform the following tasks:

  1. Send an httpGet request to the database to retrieve translations in multiple languages.

  2. Iterate through the list of translations obtained from the httpGet request.

  3. If the translation language matches what was entered in the UI fields, then send an httpPut request to update the corresponding record in the database. For example: If a user inputs a Spanish translation in the UI and the httpGet response contains Spanish translations, an httpPut request should be sent to update the Spanish record in the database.

  4. If the translation language from the UI does not exist in the httpGet results, then send an httpPost request to add a new translation record to the database. For example: If a user adds a Chinese translation in the UI and there are no Chinese translations returned by the httpGet request, an httpPost request should be sent to add the Chinese record to the database.

I have written the initial part of the code, but I understand that rxjs is non-sequential and it's not possible to use nested subscribes. Therefore, I'm looking for guidance on how to structure the rxjs statement accordingly.

p/s: The httpGet response object 'x' contains 'dataCount' and 'dataSet'. 'dataCount' represents the number of translation objects while 'dataSet' is an array containing the translation objects.

Any suggestions on how to approach writing the rxjs statement for this scenario?

this.GetTranslations(group).subscribe(x => {
  x.dataSet.forEach(translation => {
    switch (translation.Language) {
      case chineseCode:
        if (chineseInUI){
          chineseExist = true;
          let newChinese = {
            "Id": translation.Id,
            "Language": translation.Language,
            "PhraseKey": translation.PhraseKey,
            "PhraseValue": chineseInUI,
          }
          this.webApiService.httpPut$(this.resourceApiService.getURL('translationmanagerURL') + translation.Id, newChinese).subscribe();
        }
        break;
      case spanishCode:
        if (spanishInUI){
          let newSpanish = {
            "Id": translation.Id,
            "Language": translation.Language,
            "PhraseKey": translation.PhraseKey,
            "PhraseValue": spanishInUI
          }
          this.webApiService.httpPut$(this.resourceApiService.getURL('translationmanagerURL') + translation.Id, newSpanish).subscribe();
        }
        break;
    }
  });
});

Answer №1

To achieve this, you can utilize operators in the following manner:

  • mergeMap is used to generate an array of observables
  • mergeAll allows you to access the values of the inner observables within the subscription
   this.GetTranslations(group)
      .pipe(
        mergeMap((x) => {
          return x.dataSet.map((translation) => {
            switch (translation.Language) {
              case chineseCode:
                if (chineseInUI) {
                  chineseExist = true;
                  let newChinese = {
                    Id: translation.Id,
                    Language: translation.Language,
                    PhraseKey: translation.PhraseKey,
                    PhraseValue: chineseInUI,
                  };
                  return this.webApiService.httpPut$(
                    this.resourceApiService.getURL('translationmanagerURL') +
                      translation.Id,
                    newChinese
                  );
                }
                break;
              case spanishCode:
                if (spanishInUI) {
                  let newSpanish = {
                    Id: translation.Id,
                    Language: translation.Language,
                    PhraseKey: translation.PhraseKey,
                    PhraseValue: spanishInUI,
                  };
                  return this.webApiService.httpPut$(
                    this.resourceApiService.getURL('translationmanagerURL') +
                      translation.Id,
                    newSpanish
                  );
                }
                break;
            }

            return EMPTY;
          });
        }),
        mergeAll()
      )
      .subscribe((response) => {
        console.log('response', response);
      });

View a working example (with mocked data)

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 is the reason behind decorators needing to utilize apply(this) on a function?

I've been delving into the realm of JavaScript and exploring decorator code. One thing I've noticed is that when looking at decorator code like the example below, the input function always applies to 'this' even though it doesn't a ...

Utilizing JavaScript: Storing the output of functions in variables

Currently in the process of learning JavaScript and aiming to grasp this concept. Analyzed the following code snippet: function multiNum(x, y){ return x * y; } var num = multiNum(3, 4); document.write(num); Decided to try it out on my own, here's ...

Summary in Javascript

After utilizing the inspect code tool in PHPStorm, I received the following message: 'recipient_user.id === app.currentUser.id ? true : false' can be simplified to '!!(recipient_user.id === app.currentUser.id)' I'm wondering: ...

Using ES6's object destructuring to set default values for nested parameters

Utilizing es6 object destructuring for supplying default parameters to a function. function mapStateToProps({ shops: { cakeShop: {}, pieShop: {} }) { return { CakeShopName: shops.cakeShop.Name, PieShopName: shops.pieShop.Name } } An issue ari ...

Leveraging the reduce method in processing JSON data

Here is the JSON data I have: { "meta": { "totalPages": 13 }, "data": [{ "type": "articles", "id": "3", "attributes": { "title": "AAAAA", "body": "BBBB", "created": "2011-06-2 ...

What methods exist for creating visual representations of data from a table without relying on plotting libraries?

Is there a way to plot graphs directly from a Data Table without the need for external graph libraries like plotly or highcharts? Ideally, I am looking for a solution similar to ag-grid where the functionality comes built-in without requiring manual code ...

Tips for presenting JSON data retrieved using jQueryWould you like to know how

Is there a way to extract and display the user id from JSON values? I'm trying to access the user id value. $('User_id').observe('blur', function(e) { var txt = $('User_id').value; jQuery.ajax({ type: 'g ...

What could be causing my Jquery fade effect to not function properly?

I'm new to incorporating Jquery into my website and I'm facing an issue with getting the first row of pictures to fade in (upwards) when scrolling. Despite my efforts, they are not behaving as expected. Any guidance on how to resolve this? HTML: ...

Merge JSON objects into an array

Is there a way to merge JSON objects when the initial object is: { "total": "2" } And the second one is: [ "player1": { "score": "100", "ping": "50" }, "player2": { "score": "100", "ping": "50" ...

Constructor-generated element doesn't reflect changes upon component re-rendering

Why doesn't the <select> I create in the constructor update correctly when I select a different flavor? The other select and text update, but not this one. class ConstructorComponent extends React.Component { constructor() { super(); ...

Using JavaScript to manipulate an HTML canvas

I currently have an index.hTML file that is set up to display a canvas using the following code: <body> <canvas> </canvas> <script src="./JS/index.js" type="module"></script> </body> Within my JavaScript fi ...

The AXIOS method in Express.js is designed to return a Promise object that may contain an

I am currently learning ExpressJS and Axios I have created a folder named utils and placed the axios.js file const axios = require('axios'); loadDataPesan=async function(opts){ axios.get('localhost/getData', { params ...

Creating animated content with Blender and Three.js

Recently, I acquired a 3D model of an umbrella with a pre-existing animation that showcases its opening and closing. After importing it into my project using Three.js, I played the animation. To my surprise, what I thought was one animation turned out to b ...

Using Angular's dependency injection in a project that has been transpiled with Babel

I am currently attempting to transpile my Angular 6 project, which is written in TypeScript, using the new Babel 7. However, I am facing challenges with getting dependency injection to function properly. Every time I try to launch the project in Chrome, I ...

What is the best way to create JavaScript code specifically for devices with a maximum width of 520px?

Is there a way to apply this JavaScript code specifically to devices with a maximum width of 520px? I could use some guidance on how to achieve this. // Apply code for max-width = 520px const myBtn = document.getElementById("darktheme"); const ...

What is preventing the mat-slide-toggle from being moved inside the form tags?

I've got a functioning slide toggle that works perfectly, except when I try to move it next to the form, it stops working. When placed within the form tag, the toggle fails to change on click and remains in a false state. I've checked out other ...

Using Selenium 2 to dynamically insert CSS styles into the currently visible webpage

I experimented with using jQuery on a webpage that has already been modified by jQuery in order to add custom CSS code: jQuery('head').append('<style type=\"text/css\">body { background: #000; }</style>'); When I ...

Increase the number of table rows as you scroll downwards

Hello everyone! I've been searching online for information on how to implement infinite scrolling in a table, but all I found were tutorials using divs. Can someone please provide guidance on how to achieve this? Perhaps a sample code snippet or tuto ...

The router is displaying the component directly on the current page rather than opening it on a separate page

The issue is that the router is rendering the page on the same page instead of generating a new one. When clicking on the Polls link, it only renders the page there but the URL changes in the browser. Polls.js import React from 'react'; import ...

Form submission returns JSON data with an undefined value from the server

I've been following a tutorial here but ran into some issues due to using newer versions of Angular and Ionic. This is an excerpt from my code: createReview(review){ let headers = new HttpHeaders(); headers.append('Content-Type&apo ...