Unending loop caused by nested subscriptions - Angular / RxJS

I am currently implementing a nested subscribe operation, although I am aware that it may not be the most efficient method. Here is an example of what I have:

 this.route.params.subscribe((params) => {            
        this.order$
            .getMailCommande(this.id)
            .subscribe((datas) => {
                var Object = localStorage.getItem('dataCommand');
                var test = JSON.parse(retrievedObject);
                this.over = test.over;
                while (this.over == false) {
                    this.order$
                        .getMoreInfo(this.id, this.type, this.nbr)
                        .subscribe((datas2) => {
                            var array = datas2.MoreInfo;
                            var Object2 = localStorage.getItem('dataCommand');
                            var test2 = JSON.parse(Object2);
                            test2.ListeInfo.push(array);
                            this.over = true;
                        });
                }

However, the addition of the loop has resulted in an infinite loop. I am exploring the possibility of refactoring this code using switchmap or operators from RxJS, but have not yet been successful.

Does anyone have any suggestions on how to avoid the infinite loop while maintaining the same logic?

Thank you in advance.

Answer №1

If you're looking to implement a conditional loop with a break when certain conditions are met, consider creating a separate method that recursively calls itself until the condition is satisfied.

this.route.params.subscribe((params) => {            
        this.order$
            .getMailCommande(this.id)
            .subscribe((datas) => {
                var Object = localStorage.getItem('dataCommand');
                var test = JSON.parse(retrievedObject);
                this.over = test.over;
                while (this.over == false) {
                    this._loopMeOver.subscribe();
                }
            })
})


private _loopMeOver() {

    return this.order$
        .getMoreInfo(this.id, this.type, this.nbr)
        .map((datas2) => {
            var array = datas2.MoreInfo;
            var Object2 = localStorage.getItem('dataCommand');
            var test2 = JSON.parse(Object2);
            test2.ListeInfo.push(array);
            if (condition is successfull) {
                //return true mayBe
            }
            else {
                this._loopMeOver().subscribe()
            }
        });
}

Answer №2

Unfortunately, I am unable to view your complete code to fully grasp the concept of what you are attempting to achieve. However, it appears that you are in the early stages of learning rxjs and the this.over variable is being used to monitor the status of your nested request. It seems that there are multiple errors in your provided code.

It is recommended to incorporate other rxjs operators such as switchMap() to enhance the clarity of your code. I will demonstrate a basic approach using the new rxjs pipable syntax.

this.route.params.pipe(
  // The switchMap() function is triggered when there are changes in route parameters
  // The variable order$ might not be an Observable, implying its name should not end with $
  switchMap(() => this.order$.getMailCommande(this.id)),
  // The tap() operator executes after the completion of getMailCommande()
  tap(() => {
    var retrievedObject = localStorage.getItem('dataCommand');
    var test = JSON.parse(retrievedObject);
    this.over = test.over;
  }),
  // The switchMap() function executes after the tap() function
  switchMap(() => this.order$.getMoreInfo(this.id, this.type, this.nbr)),
  // The tap() function executes after getMoreInfo() completes
  tap(datas2 => {
    var array = datas2.MoreInfo;
    var Object2 = localStorage.getItem('dataCommand');
    var test2 = JSON.parse(Object2);
    test2.ListeInfo.push(array);
    this.over = true;
  })
).subscribe();

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

Run code from an inline script that is retrieved from an external origin

I am encountering an issue with my React app where I need to fetch index.html from one server location and run its scripts from another server location: const entries = await axios.get(`http://localhost:xxx`); let domParser = new DOMParser(); let tempDO ...

Show the hash codes in angular2

I need assistance with displaying hash values in angular2. The response I am receiving is in the following format: [{"1":"7"},{"2":"6"},{"3":"8"},{"4":"1"}] The key "1" represents user_id and the value "7" represents the count of posts for that user. I w ...

The operation of "grunt build" results in a Lexer Error, causing the ng-include

After deploying my unminified code successfully, I proceed to run grunt build and deploy from the dist folder. However, upon checking one of the pages, I encounter a breakage with an error in the console: Error: [$parse:lexerr] Lexer Error: Unexpected nex ...

Using Angular to open a modal by invoking the href function

Current Project Context I am currently following a tutorial on CRUD operations with DataTables, but I am using Asp.Net WebApi with Angular for this project. At step 9 of the tutorial, it introduces partial views for pop-up windows. However, instead of us ...

Error: Trying to access the 'title' property of an undefined variable in Vue.js

Creating a replica of hackernews by utilizing the axios API. The NewItem.vue component is not receiving any data, resulting in an error — TypeError: Cannot read property 'title' of undefined. Can you identify what's causing this issue in t ...

Issue arises when trying to insert an image avatar onto a globe in three.js

I have successfully implemented a rotating 3D globe using three.js with the code provided below. HTML <canvas id="canvas"></canvas> JS let camera; let renderer; function main() { const canvas = document.querySelector('#ca ...

RxJS pipe operation ignoring observable

Currently, I am in the process of transitioning an app from Promises to RxJS and I could use some guidance on whether I am heading in the right direction. Situation: I have a ModalComponent that appears when an HTTP request is sent and disappears once the ...

The Yeoman Angular Coffee router is not routing properly and displays an error message "cannot GET"

Struggling with getting the router to load a basic template after setting up a Yeoman angular scaffolder installation. Here's my configuration: // index.html <body ng-app="mvmdApp"> <div class="container" ng-view=""></div>// not ...

Enhancing Website Functionality: How to Swap iFrame for DIV using PHP and AJAX

I am currently working on a website where I need to replace an iframe containing data stored in an invisible form with a div that updates its content using AJAX. If you don't want to read everything, skip to the end for my main question. The chall ...

Creating a sidebar with child elements in Vitepress: A beginner's guide

I'm having trouble displaying my folder tree in the sidebar. When I click on a parent element like Group, the children elements are not showing up as expected. https://i.sstatic.net/kdc98.png One strange thing is that the Group elements do not have ...

Challenges encountered when using Tailwindcss and Nextjs with class and variables

Hey there, I'm currently facing a major issue with tailwindcss + nextjs... The problem lies in setting classes using a variable. Although the class is defined in the css, tailwind fails to convert it into a style. This is how I need it to be: https ...

Saving an array within the Yii framework

The view contains the following form: <form method="POST" action="<?php echo Yii::$app->request->baseUrl;?>/telephone/addnow/" role="form" enctype="multipart/form-data"> <label>Upload your photo:</label><input type="fi ...

Having trouble executing ng build --prod in Azure CICD pipelines

Having trouble setting up my application's CI/CD in Azure as the build process keeps failing. I've gone through my YAML configuration and tried multiple solutions found online, but it still doesn't work. This is the YAML setup I have: ...

Interactive planetary visualization using three.js in real-time

As I work on my react project, I'm developing a globe and looking to initialize it accurately with respect to a specific time, whether it be the current time or a future time. The goal is for this globe to correctly align itself with the day and night ...

Filter numbers within an Array using a Function Parameter

I'm currently experimenting with Arrays and the .filter() function. My goal is to filter between specified parameters in a function to achieve the desired output. However, I'm encountering an issue where my NPM test is failing. Although the outpu ...

Tips for adjusting the minimum attribute within an input field with jQuery

In my form, I have an input field with arrows (up and down). Next to it, there are two buttons: + and -. When I click on the input field and then use the arrow, the system retrieves the value from a dropdown list, which works fine. However, when I use the ...

Using JavaScript functions within PHP is not supported

Currently, I am utilizing Laravel for my backend operations. Within my setup, there exists a JavaScript function called StartJob() that facilitates Google crawling. In the scenario where I input a keyword, which is then cross-referenced with the database, ...

A textarea with a height of zero is still visible

My goal is to create collapsible widgets within a side panel on my webpage. Overall, the functionality works smoothly. I am able to adjust the height of child divs to 0px with a transition, causing them to disappear. However, I have run into an issue wher ...

Step-by-step guide: Deploying your app to Heroku with Babel and ES6 support

I've been racking my brain trying to deploy the app on Heroku. The issue is with using ES6 along with Babel. I've come across numerous articles, but none have helped me resolve the problem. Even after building the app locally and attempting to ...

Create and export a React component with dual properties

Currently, I am utilizing MaterialUI in my project and exporting components in the following manner: import withStyles, { WithStyles } from "@material-ui/core/styles/withStyles"; ... export default withStyles(styles)(Users); Recently, I have integrated ...